1 insertNode()方法:
方法可以向范围选区的开始处(光标处)插入一个节点。举个例子:
<!DOCTYPE html>
<html>
<body>
<p id="p1"><b>Hello</b> world!</p>
</body>
</html>
假设我们想在例子中的html的前面插入一下html代码:
<span style="color: red">Inserted text</span>
那么我们可以这样做:
var p1 = document.getElementById("p1");
helloNode = p1.firstChild.firstChild;
worldNode = p1.lastChild;
range = document.createRange();
range.setStart(helloNode, 2);//创造选区
range.setEnd(worldNode, 3);
var span = document.createElement("span");
span.style.color = "red";
span.appendChild(document.createTextNode("Inserted text"));
range.insertNode(span);//插入内容
结果如下:
<p id="p1"><b>He<span style="color: red">Inserted text</span>llo</b> world</p>
2 pasterHTML
pasterHTML()是一个方法,在指定的文字区域内替换该区域内文本或者HTML,但是这个方法必须要应用在一个 createTextRange() 或者 document.selection.createRange() 创建的区域上
举个例子:
<!DOCTYPE html>
<html>
<body>
<p id="p1"><b>Hello</b> world!</p>
</body>
</html>
我们先创一个范围,然后插入:
var range = document.body.createTextRange();
range.findText("Hello");
range.pasteHTML("<em>Howdy</em>");
执行后会得到这样的结果:
<p id="p1"><b><em>Howdy</em></b> world!</p>
不过,在范围内含有html时,最好不要使用这个方法,不然会很容易导致不可预料的结果.
3 innerHTML
innerHTML 属性设置或返回表格行的开始和结束标签之间的 HTML。
语法:HTMLElementObject.innerHTML=text