Notice: The following is a “best practice document”. You can follow its advice and live happily ever after, but there might be situations where you cannot apply the ideas mentioned within. This is especially the case when you have to maintain an old product or complex web application. You cannot replace everything in those in one go – as you are very lucky indeed if you get the time and budget – but you can tackle those step by step.
Working largely with b2b sites and restricted environments, I never knew it was out of fashion.
Here are some danger signs you encounter in many a bad script example and tutorials written in the spur of the moment rather than following proper research.
Things that should make you go
document.writeWhat this does is write out content to the HTML document, inside the body of the document and merrily mixed with the markup. Bad web developer, bad! Go to your corner! A better solution: reach the element you want via
getElementsByTagNameand then insert your newly created content (via
document.all , document.layers, navigator.userAgentUnless your defined project environment is MSIE 5.x and Netscape Communicator 4.x (my condolences if it is), there is no need for that any longer. Object detection is so much better than trying to guess what the browser in use is, and the W3C DOM is also more likely to be used in future UAs than the bespoke Netscape or Microsoft ones. (If you say “huh, what?” now, just trust me that everything with
document.getElementByIdis much more stable than the other two mentioned earlier)
this’ does the trick in most of the cases, as you can navigate through the DOM from there.
And what about
As some pointed out in the comments, innerHTML is another way to create content on web sites. In some cases, it is even the fastest method, as Peter-Paul Koch found out when comparing methods to generate content. However innerHTML is neither standard, nor applicable to any DOM scripting outside the browser environment. There is an excellent discussion about innerHTML on developer-x. My personal view? innerHTML makes it a lot easier, but advertises HTML documents as strings rather than node trees, and that makes it hard for junior developers to go further in their scripting ventures.