Click to See Complete Forum and Search --> : Dynamically creating a DIV in IE


yanbuwebdesign
05-26-2003, 01:54 PM
Hi everyone,

I am writing something in JS that involves dynamically creating DIVs. So this is basically how I do it:

Code:

var newDiv = document.body.appendChild (document.createElement ('div'));
newDiv.setAttribute ('id', 'someDiv');
newDiv.setAttribute ('className', 'someClass');



Now the problem is when I set any of the event-firing attributes of this newly created DIV:

Code:

newDiv.setAttribute ('onmouseover', 'alert (this.id)');



which, when rolled-over, should bring up that good old message box saying 'someDiv'. But it doesn't, so I start thinking ok I've got something wrong somewhere so I do another of those good old things:

Code:

alert (document.body.innerHTML);



and reload to get the following message:

Code:

<DIV class=someClass id=someDiv onmouseover="alert (this.id)"></DIV>



Does anyone have any idea of what is going on here? It's totally OK if I just do a document.write (blah blah) to create the div, but I want this script to run on most browsers (argh, the web-designer's dream!). Also, why does IE write the class=blah before the id=blah when I didn't set those attributes in that order. More importantly, why doesn't it include the quotes around the class="blah" or id="blah"? I tried to rectify this by doing:

Code:

newDiv.setAttribute ('id', '"someDiv"');
newDiv.setAttribute ('className', '"someClass"');



but still no use.

I know you are probably thinking I should be writing this message to Bill Gates, but I don't think he uses JS anyway!?!

OK, thanks is advance, sorry for taking long (typical Australian way, gotta get everything sorted out in every teeny-weeny detail!)

Yanbu

Khalid Ali
06-02-2003, 08:19 AM
To attache an Event to an element in IE you must use

element.attacheEvent("onclick",finctionName);

and for NS

element.addEventListener( "click", functionName, false );


some differences you must be aware of..

in IE any event name string which you might pass to the function

element.attachEvent("onclick",finctionName);

where "onclick" is the event type string.

you have to make usre its prefixed with "on" where as in NSit must not be prefixed with "on"

Hope this helps

EDIT:

Which spellings are you referring to Dave..:D