Maintain a reference to an element after insertion into the DOM

I've traditionally used JavaScript as the "UI Glue" and, unfortunately, was one of those who looked at JS as a "toy". However, I changed course and found real power in using it - especially when combined with JSON / jQuery.

My question involves creating elements dynamically and then adding them to the DOM. It looks like when this happens, only a copy of the object is added to the DOM and I lose reference to it. For example, if I create a global object using createElement (like "a"), set some attributes ("href", "title", etc.) and then add them to the DOM, any original reference to my global object does not affect the added item. I'm sure I can find the object I just inserted, but it seems like more work than it should be. Did I miss something?

0


a source to share


4 answers


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 appendChild? I'm pretty sure this is going to happen. Are you not adding it via innerHTML or something weird?



Perhaps your var is falling out of scope where you are trying to read it. (i.e. you create it in one function and read it from another?). Try to declare the object globally.

0


a source


Your original, global link should work fine. What are you trying to do about it? Do you have an example code?



0


a source


Are you using a library or something that wraps your own DOM object? This could be a problem ...

0


a source


All objects are passed by reference in JavaScript, and HTMLNodes are no exception. Your original link should always work until you assign a different value to it. It looks like you have a scope problem. Can we see the code?

0


a source







All Articles