If I have this:
<a href="#" id="the-link"><em>any random text</em></a>
Or this:
<a href="#" id="the-link">any random text</a>
Or this:
<a href="#" id="the-link"><em><div id="foo"><span>any random text</span></div></em></a>
I would like to capture the text "any random text" and then replace it.
How can I do this with jQuery? If not with jQuery, just regular javascript?
If I have this:
<a href="#" id="the-link"><em>any random text</em></a>
Or this:
<a href="#" id="the-link">any random text</a>
Or this:
<a href="#" id="the-link"><em><div id="foo"><span>any random text</span></div></em></a>
I would like to capture the text "any random text" and then replace it.
How can I do this with jQuery? If not with jQuery, just regular javascript?
Share Improve this question edited Nov 22, 2010 at 22:42 Amir asked Nov 22, 2010 at 22:33 AmirAmir 2,2777 gold badges35 silver badges48 bronze badges 2- +1 for starcraft, my favorite game. – Darin Dimitrov Commented Nov 22, 2010 at 22:35
- This is part of the DOM, or a string? – Marcel Korpel Commented Nov 22, 2010 at 22:39
4 Answers
Reset to default 5You could do this recursively. It's pretty simple:
function replaceTextNodes(node, newText) {
if (node.nodeType == 3) {
// Filter out text nodes that contain only whitespace
if (!/^\s*$/.test(node.data)) {
node.data = newText;
}
} else if (node.hasChildNodes()) {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
replaceTextNodes(node.childNodes[i], newText);
}
}
}
replaceTextNodes(document.getElementById("the-link"), "NEW TEXT");
$('a:contains(starcraft)').html('starcraft 2');
Edit for ment: jsfiddle
$('a').find(':only-child:last').html('starcraft 2');
You might want to check out this question: select deepest child in jQuery
Looks like you need to find the deepest child and then call .html('new string')
or .text('new string')
on it.
var link = $('#the-link');
var inner = link;
while(inner.children().length > 0)
inner = inner.children();
inner.html('whatever');