0

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.

sprugman
  • 19,351
  • 35
  • 110
  • 163

3 Answers3

1

The ugly way:

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

Or better:

$('input')[0].nextSibling.nodeValue = "Ipsum";
Anujith
  • 9,370
  • 6
  • 33
  • 48
1

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.

Esailija
  • 138,174
  • 23
  • 272
  • 326
0

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

However, I personally would use nodeValue.

Hope this helps!

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

Dom
  • 38,906
  • 12
  • 52
  • 81