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?
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?
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/contentspatrick 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".
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'));
Another way (not very pretty though):
$("#alvin").html($("#alvin").html().replace(/apple$/,'orange'));
Edit: Added the $ at the end of apple. Thanks Patrick.