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 />

Of course, just selecting sections of the document isn ’ t very useful unless you can interact with the<br />

selection.<br />

Interacting with DOM Range Content<br />

When a range is created, internally it creates a document fragment node onto which all of the nodes in<br />

the selection are attached. The range contents must be well formed in order for this process to take place.<br />

In the previous example, the range does not represent a well - formed DOM structure because the<br />

selection begins inside one text node and ends in another, which cannot be represented in the DOM.<br />

Ranges, however, recognize missing opening and closing tags, and are therefore able to reconstruct a<br />

valid DOM structure to operate on.<br />

In the previous example, the range calculates that a < b > start tag is missing inside the selection, so the<br />

range dynamically adds it behind the scenes, along with a new < /b > end tag to enclose “ He ” , thus<br />

altering the DOM to the following:<br />

< p > < b > He < /b > < b > llo < /b > world! < /p ><br />

Additionally, the “ world! ” text node is split into two text nodes, one containing “ Wo ” and the other<br />

containing “ rld! ” . The resulting DOM tree is shown in Figure 11 - 8 , along with the contents of the<br />

document fragment for the range.<br />

Document<br />

Element p<br />

Range<br />

DocumentFragment<br />

Element b<br />

Element b<br />

Text He<br />

Text llo<br />

Element b<br />

Text wo<br />

Text llo<br />

Text wo<br />

Text rld!<br />

Figure 11-8<br />

With the range created, the contents of the range can be manipulated using a variety of methods (note<br />

that all nodes in the range ’ s internal document fragment are simply pointers to nodes in the document).<br />

353

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

Saved successfully!

Ooh no, something went wrong!