Main Page

outerText and outerHTML

This line of code results in
<div>New text for the &lt;div/&gt;.</div>
. But what if you want to
include HTML tags inside of the element as well? That’s where
innerHTML
comes in.
The
innerHTML
property enables you to assign HTML strings to an element without worrying about
creating elements using the DOM methods. For example, suppose an empty
<div/>
needs to become
<div><strong>Hello</strong> <em>World</em></div>
. Using the DOM, this is the code you use:
var oStrong = document.createElement(“strong”);
oStrong.appendChild(document.createTextNode(“Hello”));
var oEm = document.createElement(“em”);
oEm.appendChild(document.createTextNode(“World”));
oDiv.appendChild(oStrong);
oDiv.appendChild(document.createTextNode(“”)); //space between “Hello” and “World”
oDiv.appendChild(oEm);
Using
innerHTML
, the code becomes this:
oDiv.innerHTML = “<strong>Hello</strong> <em>World</em>”;
Seven lines of code down to one line of code, that’s the power of
innerHTML
!
You can also use
innerText
and
innerHTML
to get the contents of an element. If an element has only
text,
innerText
and
innerHTML
return the exact same value. If, however, it has elements and text,
innerText
returns only the text portions, and
innerHTML
returns the HTML code for all elements and
text. The following table lists the different values for
innerText
and
innerHTML
based on certain code.
Code
innerText
innerHTML
<div>Hello world</div>
“Hello world”
“Hello world”
<div><b>Hello</b> world</div> “Hello world”
“<b>Hello</b> world”
<div><span></span></div>
“”
“<span></span>”
Ultimately, this means that you can strip out all HTML tags from a given element by setting
innerText
to equal itself:
oDiv.innerText = oDiv.innerText;
outerText and outerHTML
Along with
innerText
and
innerHTML
, Internet Explorer 4.0 also introduced
outerText
and
outerHTML
, which do exactly the same thing as their inner counterparts except that they replace the
Even though they are not part of the DOM standard, most modern browsers, includ-
ing Internet Explorer, Opera, and Safari, support
innerText
and
innerHTML
;
Mozilla supports only
innerHTML
.
315
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 315


JavaScript EditorFree JavaScript Editor     Ajax Editor


©