PPK on JavaScript: The DOM - Part 2/Page 5
[previous] [next]
PPK on JavaScript: The DOM - Part 2
Examples
I don't often use innerHTML
in the example scripts. None of them appends large structures to the document tree, and that's where innerHTML
is most useful. Nonetheless, let's review two examples where I do use innerHTML
.
innerHTML
to add the message to the page:
If the site owner wishes to add a bit of HTML to the message, he should be free to do so, and not be bothered having to write lots of extra appendChild()
lines.
I also use innerHTML
in Textarea Maxlength to add the counter to the page:
This is a clear example of innerHTML
's simplicity and power. If I'd restricted myself to pure W3C DOM methods, I'd have to do this:
Not impossible, but the first example is more concise and easier to understand.
innerHTML and pure DOM cooperation
innerHTML
and pure DOM methods cooperate perfectly; any changes you make by means of the one are immediately available to the other.
Textarea Maxlength shows that any change to the innerHTML
of an element is immediately available as part of the document tree:
First, I set the counterClone
's innerHTML
. Two lines later, I enter counterClone
by the pure DOM getElementsByTagName()
method to find the <span>
element. This works fine; the browsers understand that counterClone
now contains a <span>
, and they make it available to normal DOM methods.
The reverse also works fine. Suppose the element with ID="test" is empty:
Now the alert shows 'Test text'.
outerHTML, innerText, outerText
Together with innerHTML
, Microsoft created three other properties: outerHTML
, innerText
, and outerText
. outerHTML
works as innerHTML
, but also shows the outer tag of which it is a property. innerText
and outerText
show the text (non-HTML) contained in the tag (and no, I don't have the faintest idea how outerText
should differ from innerText
).
Take this code example:
Figure 8.15: innerHTML
, outerHTML
, innerText
, and outerText
.
innerText
as a way of reading or writing texts without going to the trouble of creating text nodes. In that case, you also need the textContent
property, which is the W3C DOM equivalent of innerText
.
element.innerText = element.textContent = 'The new text.';
These three properties are rarely used in practical Web development, partly because Mozilla doesn't support them, but mostly because the information they offer isn't very useful.
[previous] [next]
URL: