Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript add node

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?

like image 798
grep Avatar asked Oct 20 '11 16:10

grep


People also ask

What does appendChild mean in JavaScript?

appendChild() The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

How do I add a node to a DOM?

Inserting Nodes into the DOM The methods appendChild() and insertBefore() are used to add items to the beginning, middle, or end of a parent element, and replaceChild() is used to replace an old node with a new node.

Is there insertAfter in JavaScript?

jQuery insertAfter() MethodThe insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.

What does append node do?

You can use Append nodes to concatenate sets of records. Unlike Merge nodes, which join records from different sources together, Append nodes read and pass downstream all of the records from one source until there are no more.


1 Answers

You 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);
like image 93
Alex Turpin Avatar answered Oct 03 '22 23:10

Alex Turpin