Gordon wrote:
Now elements such as divs can contain more child nodes, or plain text,
or a combination of both.  What I need to know is how to get at the
text of a div with a mixture of text nodes and other HTML elements.
Doing $(element).text returns all the text in the child elements as
well, which is not what I need.  I need to do the search and replace
on the plain text inside a node, then recursivly work down through
each child node and do likewise (if it's a node of a type we want to
do replacement on).

I think you should be able to do use a function something like this:

    processTextNodes = function(element, fn) {
        var children = element.childNodes;
        for (var i = 0; i < children.length; i++) {
            var node = children[i];
            var type = node.nodeType;
            if (type == 1) processTextNodes(node, fn);
            if (type == 3) fn.call(this, node);
        }
    }

You would call it with the element you want to update and a function which accepts a single text node. So if you wanted to replace every a in the body with an @ and every e with a 3, you could do this, probably inside a $(document).ready() function:

    processTextNodes(document.body, function(node) {
        var text = node.nodeValue;
        text = text.replace(/a/g, "@");
        text = text.replace(/e/g, "3");
        node.nodeValue = text;
    });


The processTextNodes function is fairly simple, and you have to be aware that there is no requirement that browsers combine consecutive text nodes into a single nodes. That might not be a big concern, but a bigger one would be that you are receiving each text node independently, so you can't easily deal with text that spans elements. I'm not quite sure what you're going to do, but for instance, if you wanted to replace

    "something in quotes"

with

    <span class="quote">something in quotes</span>

using a regex that recognized the two quotation marks, this technique would fail on embedded elements such as

    "something <em>important</em> in quotes",

because you would operate on three separate text nodes from this string: "something ", "important", and " in quotes".

But it's pretty simple, and might get you most of what you need.

Cheers,

  -- Scott

Reply via email to