04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11: DOM Levels 2 and 3<br />

You can collapse a range by using the collapse() method, which accepts a single argument: a Boolean<br />

value indicating which end of the range to collapse to. If the argument is true , then the range is<br />

collapsed to its starting point; if it is false , the range is collapsed to its ending point. To determine if a<br />

range is already collapsed, you can use the collapsed property as follows:<br />

range.collapse(true);<br />

alert(range.collapsed);<br />

//collapse to the starting point<br />

//outputs “true”<br />

Testing whether a range is collapsed is helpful if you aren ’ t sure if two nodes in the range are next to<br />

each other. For example, consider this HTML code:<br />

< p id=”p1” > Paragraph 1 < /p > < p id=”p2” > Paragraph 2 < /p ><br />

If you don ’ t know the exact makeup of this code (for example, if it is automatically generated), you<br />

might try creating a range like this:<br />

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

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

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

range.setStartAfter(p1);<br />

range.setStartBefore(p2);<br />

alert(range.collapsed); //outputs “true”<br />

In this case, the created range is collapsed because there is nothing between the end of p1 and the<br />

beginning of p2 .<br />

Comparing DOM Ranges<br />

If you have more than one range, you can use the compareBoundaryPoints() method to determine if<br />

the ranges have any boundaries (start or end) in common. The method accepts two arguments: the range<br />

to compare to and how to compare. It is one of the following constant values:<br />

❑<br />

❑<br />

❑<br />

❑<br />

Range.START_TO_START (0) — Compares the starting point of the first range to the starting<br />

point of the second<br />

Range.START_TO_END (1) — Compares the starting point of the first range to the end point of<br />

the second<br />

Range.END_TO_END (2) — Compares the end point of the first range to the end point of the<br />

second<br />

Range.END_TO_START (3) — Compares the end point of the first range to the starting point of<br />

the second<br />

The compareBoundaryPoints() method returns – 1 if the point from the first range comes before the<br />

point from the second range, 0 if the points are equal, or 1 if the point from the first range comes after<br />

the point from the second range. Here is an example:<br />

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

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

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

range1.selectNodeContents(p1);<br />

(continued)<br />

357

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

Saved successfully!

Ooh no, something went wrong!