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>
You need to visualize the DOM structure of your
<div id="test">
element. It contains three children:A text node that contains only white space.
The
<p>
element which contains a text node that has the valueh
.A text node that has the value
ello
.So your range must start with the
<p>
element and ends in theello
text node, between the twol
characters. Therefore:Here's a fiddle.
Got it ...
In all of the documentation, they are referencing the "Child" ... this solves that. In the case of your Fiddle, it will wrap the Letter "h" and the two
<p>
and</p>
tags. Take them out and hel becomes bold.UPDATE:
Apparently, whitespace will cause problems ...
HTML ...
TEST
Working here ... jsFiddle
Reference ... HERE