dom range.setStart / setEnd

本小妞迷上赌 提交于 2019-12-04 04:09:35

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.

rfornal

Got it ...

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

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

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

range.surroundContents(newNode);

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!