18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10<br />

The following code accomplishes this:<br />

var oP1 = document.getElementById(“p1”);<br />

var oHello = oP1.firstChild.firstChild;<br />

var oWorld = oP1.lastChild;<br />

var oRange = document.createRange();<br />

var oSpan = document.createElement(“span”);<br />

oSpan.style.color = “red”;<br />

oSpan.appendChild(document.createTextNode(“Inserted text”));<br />

oRange.setStart(oHello, 2);<br />

oRange.setEnd(oWorld, 3);<br />

oRange.insertNode(oSpan);<br />

Running this <strong>JavaScript</strong> effectively creates the following HTML code:<br />

HeInserted textllo World<br />

Note that the is inserted just before the llo in Hello, which is the first part of the range selection.<br />

Also note that the original HTML didn’t add or remove elements because none of the methods<br />

introduced in the previous section were used. You can use this technique to insert helpful information,<br />

such as an image next to links that open in a new window.<br />

Along with inserting into the range, it is possible to insert content surrounding the range by using the<br />

surroundContents() method. This method accepts one parameter, which is the node that surrounds<br />

the range contents. Behind the scenes, the following steps are taken:<br />

1. The contents of the range are extracted (similar to extractContents()).<br />

2. The given node is inserted into the position in the original document where the range was.<br />

3. The contents of the document fragment is added to the given node.<br />

This sort of functionality is useful online to highlight certain words in a <strong>Web</strong> page, like this:<br />

var oP1 = document.getElementById(“p1”);<br />

var oHello = oP1.firstChild.firstChild;<br />

var oWorld = oP1.lastChild;<br />

var oRange = document.createRange();<br />

var oSpan = document.createElement(“span”);<br />

oSpan.style.backgroundColor = “yellow”;<br />

oRange.setStart(oHello, 2);<br />

oRange.setEnd(oWorld, 3);<br />

oRange.surroundContents(oSpan);<br />

The previous code highlights the range selection with a yellow background.<br />

326

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!