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.

The outerText Property<br />

Chapter 10: The Document Object Model<br />

The outerText property works in the same way as innerText except that it includes the node on<br />

which it ’ s called. For reading text values, outerText and innerText essentially behave in the exact<br />

same way. In writing mode, however, outerText behaves very differently. Instead of replacing just the<br />

child nodes of the element on which it ’ s used, outerText actually replaces the entire element, including<br />

its child nodes. Consider the following:<br />

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

This single line of code is equivalent to the following two lines:<br />

var text = document.createTextNode(“Hello world!”);<br />

div.parentNode.replaceChild(text, div);<br />

Essentially, the new text node completely replaces the element on which outerText was set. After that<br />

point in time, the element is no longer in the document and cannot be accessed.<br />

The outerText property is supported by IE, Safari, Opera, and Chrome. This property is typically not<br />

used since it modifies the element on which it is accessed. It is recommended to avoid it whenever<br />

possible.<br />

The outer HTML Property<br />

The outerHTML property is to innerHTML what outerText is to innerText . When outerHTML is called<br />

in read mode, it returns the HTML of the element on which it is called, as well as its child nodes. When<br />

called in write mode, outerHTML replaces the node on which it is called with the DOM subtree created<br />

from parsing the given HTML string. Consider the following HTML code:<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 />

When outerHTML is called on the < div > in this example, the same code is returned, including the code<br />

for the < div > . Note that there may be differences based on how the browser parses and interprets the<br />

HTML code (these are the same differences you ’ ll notice when using innerHTML ).<br />

Use outerHTML to set a value in the following manner:<br />

div.outerHTML = “ < p > This is a paragraph. < /p > ”;<br />

This code performs the same operation as the following DOM code:<br />

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

p.appendChild(document.createTextNode(“This is a paragraph.”));<br />

div.parentNode.replaceChild(p, div);<br />

305

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

Saved successfully!

Ooh no, something went wrong!