tags:

views:

314

answers:

3

I am familiar with inserting text nodes after or before a given reference node. But, I would like to know how to insert a tag between 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 user's cursor selection position) within another another node. Is that possible?

A: 

You could check a nodes innerHTML property and modify that. Alternatively you might look at childNodes collection and work with elements there (deleting the old text node and inserting new nodes in its place).

Vilx-
+3  A: 

You need to get the text into a variable then remove it from the DOM. Split it, then insert the first part, then your span node 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));
Greg
A: 

The proper way (using DOM-Core interfaces) would be:

//
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));
Sergey Ilinsky