5

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?

3
  • Why don't you just keep a reference to the variable? 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 Commented Oct 20, 2011 at 16:53
  • I also would recommend looking into jQuery. Makes DOM manipulations a breeze. Commented Oct 20, 2011 at 17:07

2 Answers 2

13

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);
Sign up to request clarification or add additional context in comments.

Comments

5

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").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.