How to get the html of a text node in jquery?

1.1k Views Asked by At

I use this as 1 of the many parts in my language translation jquery script.

This part grab's the text of a node, as I loop through all the nodes on a web page.

However it grab's a lot of the hidden javascript as a text node as well.

So is there a way to modify this, to just get the html side? And plus trim unneeded whitespace?

Here is the original code.

var content = function (node, txt) {
if (txt) {
    if (node.textContent) {
        node.textContent = txt;
    } else if (node.nodeValue) {
        node.nodeValue = txt;
    }
} else {
    return node.textContent ? node.textContent : node.nodeValue;
}

};

Here will help show the context of this code.

// recursive tree walker
(function (parent) {
    var childs = parent.childNodes;
    // if childs object has data
    if (childs && childs.length) {
        var i = childs.length; while (i--) {
            // assign node variable to childs object
            node = childs[i];
            // text node found, do the replacement
            if (node.nodeType == 3) {
                // assign the current value to a variable
                var value = content(node);

            } else {
                arguments.callee(node);
            }
        }
    }
})(document.body);

All of this is the logic my language translation code works, I just want to tweak the input so it grabs the text but no javascript code that is in the source of the page.

1

There are 1 best solutions below

4
On BEST ANSWER

Not quite sure where the function you've posted is being called from (how you're using it). Checkout this question though, which does something like what you want. The key is:

nodeType == 3

That's how you check if the DOM node is a text node. Beyond that, you may have to handle script tags specially, but you could:

:not(script)

in your jquery selector to get rid of them