Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dom range.setStart / setEnd

I am trying to bold only the text hel in this fiddle http://jsfiddle.net/yarkpakv/ but it does not seem to be working, what am I doing wrong???

var range = document.createRange();
var root_node = document.getElementById("test");

range.setStart(root_node,0);
range.setEnd(root_node,3);

var newNode = document.createElement("b");

range.surroundContents(newNode);
<div id="test">
    <p>h</p>ello    
</div>
like image 964
Karmagy Avatar asked Dec 12 '14 01:12

Karmagy


1 Answers

You need to visualize the DOM structure of your <div id="test"> element. It contains three children:

  1. A text node that contains only white space.

  2. The <p> element which contains a text node that has the value h.

  3. A text node that has the value ello.

So your range must start with the <p> element and ends in the ello text node, between the two l characters. Therefore:

var range = document.createRange();
var root_node = document.getElementById("test");

// Start at the `<p>` element.
range.setStart(root_node, 1); 

// End in the `ello` text node, between the two `l`s.
range.setEnd(root_node.childNodes[2], 2); 

var newNode = document.createElement("b");

range.surroundContents(newNode);

Here's a fiddle.

like image 94
Louis Avatar answered Nov 01 '22 16:11

Louis