JavaScript 添加节点
所以我有一个这样的函数:
var elem = document.createElement( 'svg' );
elem.id = 'svg1';
并且我希望在后面的函数中能够通过 document.getElementById('svg1')
获取此元素。
我发现这不起作用,并且通过一些研究(又名谷歌)发现,以这种方式添加元素实际上并没有将其添加到“节点树”中。如何创建一个元素以便稍后可以引用该 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将其添加到 DOM 中。例如,要将其添加为 ID 为“parent”的元素的子元素:
You need to add it to the DOM. For example, to add it as a child of an element with an ID "parent":
要将元素添加到 DOM,请执行以下操作:
将对象添加到 BODY。如果要将节点添加到另一个节点,请将
body
替换为getElementById("id")
。To add an element to the DOM you do this:
That adds the object to the BODY. If you want to add the node to another node, you replace
body
withgetElementById("id")
.