lindsay lindsay - 9 months ago 49
HTML Question

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!


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()) {