12

I want to add an element to a textNode. For example: I have a function that search for a string within element's textNode. When I find it, I want to replace with a HTML element. Is there some standard for that? Thank you.

3
  • Can you / do you want to use jQuery? Commented Oct 18, 2010 at 22:23
  • 1
    Sorry, I cannot. But BTW, show your solution to the other guys... Commented Oct 18, 2010 at 22:23
  • You already have the function to search for the string, or you're asking about that, too? Commented Oct 18, 2010 at 23:00

1 Answer 1

21

You can't just replace the string, you'll have to replace the entire TextNode element, since TextNode elements can't contain child elements in the DOM.

So, when you find your text node, generate your replacement element, then replace the text node with a function similar to:

function ReplaceNode(textNode, eNode) {
    var pNode = textNode.parentNode;
    pNode.replaceChild(textNode, eNode);
}

For what it appears you want to do, you will have to break apart the current Text Node into two new Text Nodes and a new HTML element. Here's some sample code to point you hopefully in the right direction:

function DecorateText(str) {
    var e = document.createElement("span");
    e.style.color = "#ff0000";
    e.appendChild(document.createTextNode(str));
    return e;
}

function SearchAndReplaceElement(elem) {
    for(var i = elem.childNodes.length; i--;) {
        var childNode = elem.childNodes[i];
        if(childNode.nodeType == 3) { // 3 => a Text Node
            var strSrc = childNode.nodeValue; // for Text Nodes, the nodeValue property contains the text
            var strSearch = "Special String";
            var pos = strSrc.indexOf(strSearch);

            if(pos >= 0) {
                var fragment = document.createDocumentFragment();

                if(pos > 0)
                    fragment.appendChild(document.createTextNode(strSrc.substr(0, pos)));

                fragment.appendChild(DecorateText(strSearch));

                if((pos + strSearch.length + 1) < strSrc.length)
                    fragment.appendChild(document.createTextNode(strSrc.substr(pos + strSearch.length + 1)));

                elem.replaceChild(fragment, childNode);
            }
        }
    }
}

Maybe jQuery would have made this easier, but it's good to understand why all of this stuff works the way it does.

Sign up to request clarification or add additional context in comments.

1 Comment

Do you have any examples? Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.