Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert HTML after String / String position

I've come up short on an answer for this so hopefully there's someone who can help me.

I'm trying to non-destructively insert HTML before and after a substring or position in text to create new inline elements or wrap existing text. I would just use innerHTML and be done with this already but I would really like to preserve possible event listeners that might be bound to that particular DOMNode. Is there a method or a prototype of a Element that treats textNodes as individual items that would allow me to append HTML after or before it?

The code might operate like this:

var testParagraph = document.getElementById("TestParagraph");

/** 
    text nodes would represent each item 
    that has been seperated by a space, for example 
**/

testParagraph.insertBefore(document.createElement("span"), testParagraph.textNodes[3])

Thanks for your time!

like image 519
lindsay Avatar asked Apr 20 '26 18:04

lindsay


1 Answers

If you want to insert dom elements into text, then there will not be an issue of event handlers since event handlers can not be bound onto the text itself. It's possible, and easier than you might think, to change the content of a DOM element without destroying any event handlers.

function insertAtStringPos(el, pos, insertable) {
    if(!el.children.length) {
        var text      = el.outerText;
        var beginning = document.createTextNode(text.substr(0, pos));
        var end       = document.createTextNode(text.substr(pos - text.length));

        while (el.hasChildNodes()) {
            el.removeChild(el.firstChild);
        }

        el.appendChild(beginning);
        el.appendChild(insertable);
        el.appendChild(end);
    }
}

Example: http://jsfiddle.net/9a8rxhp4/

like image 92
bitten Avatar answered Apr 23 '26 08:04

bitten