0

I have a td with this format:

<td>
    Business Owner - Delivery Director <br>
    <a href="mailto:me@business.com">me@business.com</a>
</td>

How can I only replace the text "Business Owner - Delivery Director" with something else?

Using this.text() fetches Business Owner - Delivery Director and me@business.com, but I want only Business Owner - Delivery Director.

Cerbrus
  • 65,559
  • 18
  • 128
  • 140
user1184100
  • 6,556
  • 29
  • 77
  • 118

4 Answers4

6

You can use the childNodes property to select the first text node and change its value:

$('td')[0].childNodes[0].nodeValue = "New content";

Here is a demonstration: http://jsfiddle.net/dpyNy/

Asad Saeeduddin
  • 45,116
  • 6
  • 87
  • 135
2

Use .contents() to get the text node (with CharacterData interface) and then manipulate its content:

$("td").contents()[0].data = "Businees Owner (CEO)";

Demo at jsfiddle.net

Bergi
  • 572,313
  • 128
  • 898
  • 1,281
1

With that structure, you'll have to do string manipulation, either using split:

var td = $("selector_for_the_td_element");
var text = td.html().split("<br>");
text[0] = "new content";
td.html(text.join("<br>"));

...or using indexOf and substring:

var td = $("selector_for_the_td_element");
var text = td.html();
var index = text.indexOf("<br>");
text = "new content" + text.substring(index);
td.html(text);

Now, if you can change your HTML structure to this:

<td>
    <span>Business Owner - Delivery Director</span><br>
    <a href="mailto:me@business.com">me@business.com</a>
</td>

...it gets a lot easier:

$("selector_for_the_td_element > span").text("new content");
T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
  • @Bergi: That's how I read it. *"How can I only replace the text..."* and *"`this.text() gives me..."*. Granted this is possible using the text nodes, but as he's clearly using jQuery, a jQuery-oriented solution's reasonable. (Upvoted Asad for the other, though.) – T.J. Crowder Dec 07 '12 at 09:59
  • 1
    @Bergi: The OP hasn't mentioned any preference in regards to "HTML manipulation". T.J: I like the `span` suggestion, good practice. – Cerbrus Dec 07 '12 at 10:00
-1

If the html structure is exactlly what you post, you can achieve it like this:

this.childNodes[0].nodeValue = 'hello'; //this is the td element
dencey
  • 1,031
  • 16
  • 25
  • I assume you mean the `td` with `this`, but that's a pretty poor choice of variable names. – Cerbrus Dec 07 '12 at 10:05
  • @Cerbrus It's not a variable name and 'this' cannot be a variable name in javascript, i just write it following the context in the question , maybe it's in an event handler environment, why can you say it's a poor name just according to this snippet? – dencey Dec 07 '12 at 10:10
  • Oh, I missed the `this` in his question. Forget I said anything :-P – Cerbrus Dec 07 '12 at 10:11