Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all urls in a div

I am trying to write javascript code to find all the urls inside a div. Now this would be pretty easy if all the urls within the div were separated by spaces in which case I can just do a regex on what's inside the div to find them. However, the urls within this outer div may be in sub divs (or any other html tag) and I want to consider the subdivs as separators as well (and I don't want to get rid of these subdivs). To give an example, in the following I want to find www.foo.com and www.bar.com within the div with id "outer":

<div id="outer"><div>www.foo.com</div>www.bar.com</div>

What would be a good way of doing this?

like image 364
shoopdelang Avatar asked Jun 05 '13 04:06

shoopdelang


1 Answers

You can apply a recursive call to all non-text child nodes.

function replaceWwwInNodes(node) {
    //text node
    if (node.nodeType === 3) {
        node.textContent = node.textContent.replace(/* ??? */)
    }
    else {
        Array.prototype.forEach.call(node.childNodes, function (elem) {
            replaceWwwInNodes(elem);
        });
    }
}

replaceWwwInNodes(document.getElementById('outer'));

http://jsfiddle.net/UDX5V/

like image 95
Explosion Pills Avatar answered Oct 23 '22 02:10

Explosion Pills