最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - Javascript add node - Stack Overflow

programmeradmin0浏览0评论

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
Add a comment  | 

2 Answers 2

Reset to default 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);

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

发布评论

评论列表(0)

  1. 暂无评论