↑
Main Page
innerText and innerHTML
}
</style>
<script type=”text/javascript”>
function getBackgroundColor() {
var oDiv = document.getElementById(“div1”);
alert(document.defaultView.getComputedStyle(oDiv,
null).backgroundColor);
}
</script>
</head>
<body>
<div id=”div1” class=”special”></div>
<input type=”button” value=”Get Background Color”
onclick=”getBackgroundColor()” />
</body>
</html>
DOM-compliant browsers running this example display the background color in an alert when the but-
ton is clicked.
innerText and innerHTML
Despite the advantages that the DOM brought to dynamically modifying documents, it wasn’t enough
for the developers at Microsoft. Internet Explorer 4.0 introduced two properties on all elements designed
to ease the manipulation of the document called
innerText
and
innerHTML
.
The
innerText
property is designed to modify text between a starting and ending tag. For example,
suppose you have an empty
<div/>
element that you wanted to change to
<div>New text for the
div.</div>
. Using the DOM, you do this:
oDiv.appendChild(document.createTextNode(“New text for the div.”));
This code isn’t difficult, but it is a bit verbose. Using
innerText
, you can just do this:
oDiv.innerText = “New text for the div.”;
Using
innerText
, the code is much simpler and easier to understand. Additionally,
innerText
auto-
matically HTML-encodes any less-than, greater-than, quote, and ampersand characters so you never
have to worry about them:
oDiv.innerText = “New text for the <div/>.”;
Note that although some browsers support this functionality, the manner in which
values are represented can differ. For example, Mozilla translates all colors into RGB
form (
rgb(255,0,0)
for red), whereas Opera translates all colors into their hexa-
decimal representations (
#ff0000
for red). It’s always best to test your functionality
on a number of browsers when using
getComputedStyle()
.
314
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 314
Free JavaScript Editor
Ajax Editor
©
→