View Full Version : Create an element at script location

07-01-2006, 07:42 PM
Hello all! I've come back from my long vacation in the land of not-using-javascript!
Take a look at http://www.pitt.edu/~jrf27/links.html
Ignore the terrible page. I know it's awful. I'm working on that.

I made the game on the left side of the page two months ago in C++, and a month ago translated it to TI-BASIC on the TI-83, and then yesterday moved it to javascript. I've goota say, Javascript is the way to go! My headaches of TI-BASIC were instantly relieved when I went back to Javascript.

Now for my problem. There isn't really a problem in the sense that the game is fully functional, it's more of just something that bugs me. I created the game in hopes of making it as unobtrusive as possible to the page. The entire game uses 3 css classes and one JS Object named bloc. I want the game to generate its own div to live within, which it currenyl does, but I want the div to be name-less and ID-less, so other scripts in any page will not interfere.
Now to the code:

//Line 28 of bloc.js:
document.writeln("<div id=\"bloc.par\"></div>");

//Line 32 of bloc.js:
bloc.par = document.getElementById("bloc.par");

This is everything that is making me restless. I want that div to be ID-less. How can I create a div, and have it appear in the DOM structure immediately after the script tags that called bloc.gen(), and still be able to reference it later?

One solution that I came up with was this:

<div><img src="someimage.gif" onload="bloc.par=this.parentNode;bloc.gen();" /></div>

But it doesn't validate. Yeah yeah yeah. I have a perfectly acceptable solution but I'd rather not use it. Please don't be hatin.


07-01-2006, 10:34 PM
If you used DOM methods to add the <div> instead of document.write(), you could save a reference to it in a variable that you could use later.

JavaScript tutorial - W3C DOM introduction (http://www.howtocreate.co.uk/tutorials/javascript/domintroduction)

07-02-2006, 12:30 AM
After writing a few test scripts, I found that FF considers the text within a script tag to be a child of the script, but IE considers the script tag to be the last element in the heirarchy. So...

bloc.par = document.documentElement;
while (bloc.par.lastChild.nodeName!="SCRIPT") bloc.par = bloc.par.lastChild;
bloc.par = bloc.par.appendChild(document.createElement("div"));

Seems to be a working solution. Thanks!