I have some reusable components that can either be added to the page after the fact, or created during the initial render. In the past, when I needed to display content with javascript during the initial render I have used document.write().
However, in the spirit of keeping things as clean and reusable as possible, I have been considering making everything using DOM calls (from low level "createElement" to the higher level innerHTML approach, often combining the two as in the example below). This allows me more flexibility than document.write(). However, I often want to display the elements during the initial render so that the page comes in as cleanly as possible -- if I add it in the body.onload event, it can look ugly to the user.
Is this approach ok? My experimentation seems to work alright, but since I never see it in examples on the web, I'm worried it is an unsanctioned approach and might fail in some browsers. For instance, creating a div in html, and then immediately getting the element by its id (before the rest of the page has rendered) and sticking something in that div.....it that ok? Is there any advantage to document.write() in this situation? (aside from running in pre-DOM browsers)
Here is basically how I do it (in reality it would be used for very complex things, such as a table or something....):
<html><body>
<div id="foo">
</div>
<script language="javascript">
var elem = document.createElement("A"
);
elem.innerHTML = "go to yahoo";
elem.setAttribute ("class", "whatever");
elem.href = "
http://www.yahoo.com";
document.getElementById ("foo").appendChild (elem);
</script>
</body></html>
I'd be particularly interested in seeing examples on the web where such an approach is used.
thanks
Start Free Trial