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 ?
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'; Sorry for the late answer ... But here is a way to do this using only jQuery:
$('label').contents().last().replaceWith("Title"); This may not be the most beautiful way, but it works:
var $label = $('label[for=user_name]'); $label.html($label.html().replace("Name", "Title")); 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
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/
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');
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'; 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.