powerboy
powerboy

Reputation: 10961

replace a textnode that has non-textnode siblings

For this HTML

<label id="nameWrapper"><input type="checkbox" name="name" />guest</label>

What's the shortest javascript code to replace guest with other text? What I can think of is,

$('#nameWrapper').contents().filter(function() {
  return this.nodeType == 3;
}).replaceWith('other text');

Upvotes: 2

Views: 107

Answers (1)

user113716
user113716

Reputation: 322492

Non-jQuery method.

Example: http://jsfiddle.net/patrick_dw/NLJ3e/

document.getElementById('nameWrapper').lastChild.data = 'new text';

Or shorten it with a jQuery selector:

Example: http://jsfiddle.net/patrick_dw/NLJ3e/1/

$('#nameWrapper')[0].lastChild.data = 'new text';

Or a little longer (and slower), but more jQuery-like:

Example: http://jsfiddle.net/patrick_dw/NLJ3e/2/

$('#nameWrapper').contents().last().replaceWith('new text');

Upvotes: 3

Related Questions