sprugman
sprugman

Reputation: 19831

Updating "text" nodes with jQuery

I have html like:

<label><input type="radio" /> Lorem</label>

What's the best way to change "Lorem" to "Ipsum"? These don't work:

// nope:
$('input').next().text('Ipsum'); 

// also nope:
var text = $('input').parent()[0].childNodes[1];
$(text).text('Ipsum');

I can easily change the html to:

<label><input type="radio" /><span> Lorem</span></label>

or use the replaceWholeText DOM method directly:

$('input').parent()[0].childNodes[1].replaceWholeText(' Ipsum');

or any number of other things, but I'm wondering if there's a clean jQuery way to do this.

Upvotes: 0

Views: 134

Answers (3)

Dom
Dom

Reputation: 40461

$('label').contents().last().replaceWith("Ipsum");

However, I personally would use nodeValue.

Hope this helps!

DEMO: http://jsfiddle.net/dirtyd77/SLGdE/25/

Upvotes: 0

Anujith
Anujith

Reputation: 9370

The ugly way:

 $('input').parent().contents().each(function(){
   if(this.nodeType === 3)
     this.nodeValue= "Ipsum";
 });

Or better:

$('input')[0].nextSibling.nodeValue = "Ipsum";

Upvotes: 1

Esailija
Esailija

Reputation: 140210

jQuery doesn't have any first class text node support. You could:

$("input")[0].nextSibling.nodeValue = "Ipsum";

Or use a <span> with an identifier or class and target that. If you need to change the text dynamically it probably warrants a container like that.

Upvotes: 1

Related Questions