* Name A...">

How to change only node text in an element

I have the following html:

<label for="user_name"> <abbr title="required">*</abbr> Name </label> 

And I want to change the caption to Title using jquery. Therefore i do

 $('label[for=user_name]').html('Title') 

And it will replace all internal html (with abbr tag)

So what is the easiest way to replace only Name ?

+38
jquery
Mar 31 '12 at 13:43
source share
8 answers

If you use the contents() method, it will also return text nodes. Since jQuery does not have node text methods, convert the latest node to a DOM node

 $('label[for="user_name"]').contents().last()[0].textContent='Title'; 

Demo: http://jsfiddle.net/yPAST/1/

+57
Mar 31 2018-12-12T00:
source share

Sorry for the late answer ... But here is a way to do this using only jQuery:

 $('label').contents().last().replaceWith("Title"); 
+34
Mar 14 '13 at 17:23
source share

This may not be the most beautiful way, but it works:

 var $label = $('label[for=user_name]'); $label.html($label.html().replace("Name", "Title")); 
+2
Mar 31 2018-12-12T00:
source share

You can only select the abbr element, save it, and then replace all the content with the saved element plus the changed title:

 ​$('label[for="user_name"]').each(function(){ var a = $(this).children('abbr'); $(this).html(a).append('Title'); }); 

See fiddle

+1
Mar 31 2018-12-12T00:
source share

you can use replace execute

  var html = $('label[for=user_name]').html().replace('Name','Testing'); $('label[for=user_name]').html(html); 

check: http://jsfiddle.net/DyzMJ/

+1
Mar 31 '12 at 14:01
source share

Evans solution added in jquery fn to make it convenient:

 // get/change node content not children jQuery.fn.content = function( n ){ var o = $(this).clone(); var c = o.children().remove(); if (typeof n === "string" ){ o.html(n); $(this).html(c).append(n); } return o.html(); } 

Usage: $('myselector').content('NewContentString');

+1
Jan 13 '13 at 13:01
source share

This is a solution that worked for most browsers.

 $('label[for="user_name"]').contents().last()[0].nodeValue = 'Title'; 

This one came close but gave problems in ie8 as textContent is not supported

 $('label[for="user_name"]').contents().last()[0].textContent='Title'; 
0
Jun 26 '13 at 22:22
source share

If you are manipulating more than 1 tag, you can select each tag and replace the text with jquery:

 $('label[for="user_name"]').contents().last().replaceWith("Title"); 

and for the second label:

 $('label[for="user_lastname"]').contents().last().replaceWith("Title2"); 

etc.

0
Oct 07 '15 at 11:35
source share



All Articles