Javascript add node

So, I have a function like this:

var elem = document.createElement( 'svg' ); elem.id = 'svg1'; 

and I would like, in a later function, to be able to capture this element through document.getElementById('svg1') .

I found this to not work, and through some research, also known as google, I found that adding an element in this way does not actually add it to the node tree. How can I create an element to subsequently reference an Id?

+4
source share
2 answers

You need to add it to the DOM. For example, to add it as a child of an element with the identifier "parent":

 document.getElementById("parent").appendChild(elem); 
+11
source

To add an item to the DOM, do the following:

 document.body.appendChild(elem); 

This adds the object to BODY. If you want to add a node to another node, you replace the body with getElementById("id") .

+5
source

All Articles