Pete Alvin
Pete Alvin

Reputation: 4790

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?

Upvotes: 8

Views: 9393

Answers (4)

artlung
artlung

Reputation: 34013

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'));

Upvotes: 1

Gert Grenander
Gert Grenander

Reputation: 17084

Another way (not very pretty though):

$("#alvin").html($("#alvin").html().replace(/apple$/,'orange'));

Edit: Added the $ at the end of apple. Thanks Patrick.

Upvotes: 0

user113716
user113716

Reputation: 322492

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.

Upvotes: 13

Andy E
Andy E

Reputation: 344575

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/

Upvotes: 6

Related Questions