Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: How replace text AFTER a nested tag?

I'm trying to figure out the jQuery statement to rename "apple" with "orange:"

<a id="alvin" href="http://www.camille.com"><ins class="xxx">Anna</ins>apple</a>

Can this be done easily?

like image 442
Pete Alvin Avatar asked Jun 13 '10 01:06

Pete Alvin


3 Answers

I removed the # from the ID, since it is not a valid ID character.

Given that, try this:

Live Example: http://jsfiddle.net/u49wy/

var $contents = $('#alvin').contents();

$contents[$contents.length - 1].nodeValue = 'orange';

.contents() returns all the child nodes of the element, including text nodes.

The code then grabs the last element node (which is a text node) and updates its nodeValue, which is how you update the value of a text node.

  • .contents() - http://api.jquery.com/contents
like image 50
user113716 Avatar answered Oct 28 '22 04:10

user113716


patrick beat me to it, but my solution is a little more dynamic in that it would select the text anywhere, even if there were tags on either side:

$('#alvin').contents().filter(function () {
    return this.nodeType == 3;
})[0].nodeValue = "orange";

It does this by filtering the contents so that only text nodes remain, and changes the first nodeValue to "orange".

http://jsfiddle.net/ssRyB/

like image 6
Andy E Avatar answered Oct 28 '22 05:10

Andy E


id="#alvin" is not valid syntax, '#' is used as part of a selector for jQuery or in CSS.

For this very limited example, replace "apple" with "orange" I would actually simply read the innerHTML and rewrite it. I'm not even using jQuery for this.

window.onload = function() {
    var alvin = document.getElementById('alvin')
    alvin.innerHTML = alvin.innerHTML.replace('apple', 'orange');
}

I used no jQuery because jQuery does not have a clean way to select stray text nodes. So what if we wrapped any child text nodes in spans? We could do this:

$('#alvin').contents().filter(function() {
  return this.nodeType == 3;
}).wrap('<span></span>').end();

In that way, we are left with the structure:

<a id="alvin" href="http://www.camille.com"><ins class="xxx">Anna</ins><span>apple</span></a>

Then we can use the + adjacent selector to get at it, like this -- ins+span means a <span> after an <ins>:

var elem = $('#alvin ins+span');
elem.text(elem.text().replace('apple', 'orange'));
like image 1
artlung Avatar answered Oct 28 '22 04:10

artlung