Main Page

outerHTML

node in question. For example, setting
outerText
on a
<div/>
removes it and replaces it with a text node.
Consider the following line of code:
oDiv.outerText = “Hello world!”;
This single line of code is the same as this set of DOM manipulations:
var oText = document.createTextNode(“Hello world! “);
var oDivParent = oDiv.parentNode;
oDivParent.replaceChild(oText, oDiv);
The
outerText
property has the same rules as the
innerText
property in that it replaces all less-than,
greater-than, quote, and ampersand characters with their HTML entities. Similarly,
outerHTML
behaves
the same as
innerHTML
, creating all the necessary DOM nodes represented by the HTML string:
oDiv.outerHTML = “<p>This is a paragraph.</p>”;
This line of code performs the following DOM modifications:
var oP = document.createElement(“p”);
oP.appendChild(document.createTextNode(“This is a paragraph. “));
var oDivParent = oDiv.parentNode;
oDivParent.replaceChild(oP, oDiv);
Whereas
outerText
and
outerHTML
provide developers with a lot of power, they don’t clearly indicate
exactly what is happening (the code doesn’t
read
). Many developers shy away from using
outerText
and
outerHTML
because they can lead to bigger headaches down the road if something goes wrong.
Generally speaking, you’re safer using the DOM methods, whose meanings are much clearer.
Both these properties can also be used to get the contents of an element. The
outerText
property
always returns the same value as
innerText
, regardless of the element contents. On the other hand,
outerHTML
returns the full HTML code for the element, including the element itself. The following table
lists the different values for
outerText
and
outerHTML
based on certain code.
Code
outerText
outerHTML
<div>Hello world</div>
“Hello world” “<div>Hello world</div>”
<div><b>Hello</b>
world</div>
“Hello world” “<div><b>Hello</b> world</div>”
<div><span></span></div> “”
“<div><span></span></div>”
Similar to
innerText
, you can use
outerText
in a unique way. By setting
outerText
equal to itself, you
actually remove the element and replace it with a text node containing all the text inside the element:
<html>
<head>
<title>OuterText Example</title>
<style type=”text/css”>
div.special {
316
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 316


JavaScript EditorFree JavaScript Editor     Ajax Editor


©