04.11.2015 Views

javascript

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: The Document Object Model<br />

< div id=”content” ><br />

< p > This is a < strong > paragraph < /strong > with a list following it. < /p ><br />

< ul ><br />

< li > Item 1 < /li ><br />

< li > Item 2 < /li ><br />

< li > Item 3 < /li ><br />

< /ul ><br />

< /div ><br />

For the < div > element in this example, the innerText property returns the following string:<br />

This is a paragraph with a list following it.<br />

Item 1<br />

Item 2<br />

Item 3<br />

Note that different browsers treat white space in different ways, so the formatting may or may not<br />

include the indentation in the original HTML code.<br />

Using the innerText property to set the contents of the < div > element is as simple as this single line<br />

of code:<br />

div.innerText = “Hello world!”;<br />

After executing this line of code, the HTML of the page is effectively changed to the following:<br />

< div id=”content” > Hello world! < /div ><br />

Setting innerText removes all of the child nodes that existed before, completely changing the DOM<br />

subtree. Additionally, setting innerText encodes all HTML syntax characters (less - than, greater - than,<br />

quotation marks, and ampersands) that may appear in the text. Here is an example:<br />

div.innerText = “Hello & welcome, < b > \”reader\”! < /b > ”;<br />

The result of this operation is as follows:<br />

< div id=”content” > Hello & amp; welcome, & lt;b & gt; & quot;reader & quot;! & lt;/b & gt; < /div ><br />

Setting innerText can never result in anything other than a single text node as the child of the<br />

container, so the HTML - encoding of the text must take place in order to keep to that single text node.<br />

The innerText property is also useful for stripping out HTML tags. By setting the innerText equal<br />

to the innerText , as shown here, all HTML tags are removed:<br />

div.innerText = div.innerText;<br />

Executing this code replaces the contents of the container with just the text that exists already.<br />

The innerText property is supported in IE, Safari, Opera, and Chrome. Firefox does not support<br />

innerText, but it supports an equivalent property called textContent . The textContent property is<br />

301

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

Saved successfully!

Ooh no, something went wrong!