Jake Barnes wrote:
Just to follow up on this, I'm hoping this is a real simple question,
but if I want to dynamically add this line to a page, how do I do it?
<h1>You're the greatest!</h1>
Right now I'm assigning it to the innerHTML of the divs, and that
works, but I'm told I'm not suppose to use innerHTML. What would be the
DOM way to do this?
HTML:
<div id="divA"></div>
Script & W3C DOM:
if (document.getElementById && document.createElement){
var divA = document.getElementById('divA');
var oH = document.createElement('h1');
oH.appendChild(document.createTextNode('You\'re the greatest'));
// Insert the heading as the first child of the element
divA.insertBefore(oH, divA.firstChild);
}
The same thing done with innerHTML would be something like:
if (document.getElementById){
var divA = document.getElementById('divA');
var aHTML = divA.innerHTML;
if ('string' == typeof aHTML){
// Insert the heading at the start of the element
divA.innerHTML = aHTML + <h1>You\'re the greatest</h1>';
}
}
Some reasons not to use innerHTML:
1. There are differences between implementations (as you discovered),
but there is no public standard so you can't say what is right or wrong
behaviour. Since it was invented by MS for IE, you could say that
whatever IE does it right and anything else is wrong.
2. Replacing the innerHTML means that the browser must re-parse and
re-render everything, whereas with DOM the effort should be less - you
are only adding/removing bits.
3. innerHTML has to be put inside something, it's very hard to insert a
new element between two others. MS also invented insertAdjacentElement,
insertAdjacentHTML and insertAdjacentText to do that. The same
functionality is provided W3C DOM methods appendChild and insertBefore
(which are also supported by IE).
4. It is harder to debug scripts that use innerHTML, it's kind of a
black box since the JS engine squirts HTML at the rendering engine and
generally any errors in the HTML are not reported back, so you don't
really know if it works or not.
The bottom line is that DOM methods are more widely supported (i.e. more
browsers support them) and generally use a simpler set of instructions
to achieve the same goal (it's a bit like CISC vs RISC in that regard).
The best idea is to code using a Gecko browser (say Firefox or Mozilla),
then test in others, particularly IE. Some really like Opera, Safari is
OK for development but I prefer Firefox (though I prefer to surf the web
using Safari).
--
Rob