Insert node between text

I am familiar with inserting text nodes after or before a given node link. But I would like to know how to insert a tag between the text in a given node. For example,

Before insertion: <p>Lorem dolor</p> After insertion: <p>Lorem <span>ipsum</span> dolor</p> 

The span node must be inserted after N characters (I don’t need the position of the user's cursor selection) in another other node. Is it possible?

+6
javascript dom
source share
3 answers

The correct way (using the DOM-Core interfaces):

 var p = document.getElementById('myParagraph'); var text = p.childNodes[0]; var at = 5; // create new span node with content var span = document.createElement("span"); span.appendChild(document.createTextNode('ipsum')); // Split the text node into two and add new span p.insertBefore(span, text.splitText(at)); 
+13
source share

You need to get the text in the variable and then remove it from the DOM. Separate it, then insert the first part, then your node range, then the second part.

 var p = document.getElementById('myParagraph'); var text = p.childNodes[0]; // Split the text var len = 5 var text1 = text.nodeValue.substr(0, len); var text2 = text.nodeValue.substr(len); var span = document.createElement('span'); span.appendChild(document.createTextNode(' dolor')); // Remove the existing text p.removeChild(p.childNodes[0]); // Put the new text in p.appendChild(document.createTextNode(text1)); p.appendChild(span); p.appendChild(document.createTextNode(text2)); 
+11
source share

You can check the node innerHTML property and change it. Alternatively, you can look at the childNodes collection and work with the elements there (delete the old text node and insert new nodes in their place).

+1
source share

All Articles