Main Page

Web page

The following code accomplishes this:
var oP1 = document.getElementById(“p1”);
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
var oRange = document.createRange();
var oSpan = document.createElement(“span”);
oSpan.style.color = “red”;
oSpan.appendChild(document.createTextNode(“Inserted text”));
oRange.setStart(oHello, 2);
oRange.setEnd(oWorld, 3);
oRange.insertNode(oSpan);
Running this JavaScript effectively creates the following HTML code:
<p id=”p1”><b>He<span style=”color: red”>Inserted text</span>llo</b> World</p>
Note that the
<span/>
is inserted just before the
llo
in
Hello
, which is the first part of the range selec-
tion. Also note that the original HTML didn’t add or remove
<b/>
elements because none of the methods
introduced in the previous section were used. You can use this technique to insert helpful information,
such as an image next to links that open in a new window.
Along with inserting into the range, it is possible to insert content surrounding the range by using the
surroundContents()
method. This method accepts one parameter, which is the node that surrounds
the range contents. Behind the scenes, the following steps are taken:
1.
The contents of the range are extracted (similar to
extractContents()
).
2.
The given node is inserted into the position in the original document where the range was.
3.
The contents of the document fragment is added to the given node.
This sort of functionality is useful online to highlight certain words in a Web page, like this:
var oP1 = document.getElementById(“p1”);
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
var oRange = document.createRange();
var oSpan = document.createElement(“span”);
oSpan.style.backgroundColor = “yellow”;
oRange.setStart(oHello, 2);
oRange.setEnd(oWorld, 3);
oRange.surroundContents(oSpan);
The previous code highlights the range selection with a yellow background.
326
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 326


JavaScript EditorFree JavaScript Editor     Ajax Editor


©