So I have a function like such:
var elem = document.createElement( 'svg' );
elem.id = 'svg1';
and I would like to, in a later function, be able to grab this element via document.getElementById('svg1')
.
I have found this does not work, and through some research, aka google, found that adding an element this way does not actually add it to the 'node tree'. How can I create an element so I can later reference the Id?
So I have a function like such:
var elem = document.createElement( 'svg' );
elem.id = 'svg1';
and I would like to, in a later function, be able to grab this element via document.getElementById('svg1')
.
I have found this does not work, and through some research, aka google, found that adding an element this way does not actually add it to the 'node tree'. How can I create an element so I can later reference the Id?
Share Improve this question asked Oct 20, 2011 at 16:50 grepgrep 4,0168 gold badges46 silver badges67 bronze badges 3- Why don't you just keep a reference to the variable? – epascarello Commented Oct 20, 2011 at 16:53
- looks like you stopped googling too soon. Append the node to the document. javascriptkit.com/javatutors/dom2.shtml. JQuery also simplifies this. api.jquery.com/append – Visionary Software Solutions Commented Oct 20, 2011 at 16:53
- I also would recommend looking into jQuery. Makes DOM manipulations a breeze. – Alex Turpin Commented Oct 20, 2011 at 17:07
2 Answers
Reset to default 13You need to add it to the DOM. For example, to add it as a child of an element with an ID "parent":
document.getElementById("parent").appendChild(elem);
To add an element to the DOM you do this:
document.body.appendChild(elem);
That adds the object to the BODY. If you want to add the node to another node, you replace body
with getElementById("id")
.