Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the inner most text with javascript (jquery) regardless of number of nested elements and replace it

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?

like image 562
Amir Avatar asked Jan 22 '23 01:01

Amir


2 Answers

You 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");
like image 95
Tim Down Avatar answered Mar 30 '23 00:03

Tim Down


$('a:contains(starcraft)').html('starcraft 2');

Edit for comment: jsfiddle

$('a').find(':only-child:last').html('starcraft 2');
like image 23
Josiah Ruddell Avatar answered Mar 29 '23 23:03

Josiah Ruddell