tags:

views:

122

answers:

4

I've traditionally used JavaScript as "UI Glue", and have (regrettably) been one of those that looked at JS as a "toy". However, I've changed course and am finding some real power in its use - especially coupled with JSON/jQuery.

My question involves dynamically creating elements, then appending them to the DOM. It seems that when this happens, only a copy of the object is appended to the DOM and I lose the reference to it. For example, if I create a global object using createElement (say, "a"), set a few attributes ("href", "title", etc.) and then append it into the DOM, any original reference to my global object has no impact on the appended element. I'm sure that I could find the object I just inserted, but this seems like more work than it should be. Am I missing something?

A: 
var new_div = document.createElement('div');
new_div.id = 'foo';

EDIT: Just re-read your question, are you saying new_div doesn't work after an appendChild? I'm pretty sure it should. You're not adding it via innerHTML or something strange like that?

Maybe your var is falling out of scope where you are trying to read it. (ie, you are creating it in one function and reading it from another?). Try declaring the object globally.

SpliFF
I found the issue. I was trying to set attributes of the object by using, strangely enough, "setAttribute". It appears that IE doesn't like that for very many things. Drilling down objectively fixed the issue - for example el.style.color = 'green' works, el.setAttribute("style", "color:green;") fails.
BradBrening
Yes, there area few HTML attributes that IE versions earlier than 8 don't support, notably class and style. However, it should largely be a non-issue. Style attributes should be set through the elem.style properties, and the class should be set through the elem.className property.
Andrew Noyes
A: 

Your original, global, reference should still work fine. What are you trying to do with it? Do you have any example code?

AgileJon
A: 

Are you using a library or something that is wrapping a native DOM object?, this might be the problem...

SleepyCod
A: 

All objects are passed by reference in JavaScript, and HTMLNodes are no exception. Your original reference should always work until you assign it a different value. Sounds like you have a scope issue. Could we see the code?

Andrew Noyes