javascript 使用 document.createElement 创建嵌套标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11840858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating nested tags using document.createElement
提问by my name is xyz
I want to create a nested tag using javascript createElementfunction like
我想使用 javascript createElement函数创建一个嵌套标签,例如
<li><span class="toggle">Jan</span></li>
Can anyone give me an idea how to do it?
谁能给我一个想法如何做到这一点?
回答by jfriend00
The simplest way is with createElement()
and then set its innerHTML
:
最简单的方法是使用createElement()
然后设置它的innerHTML
:
var tag = document.createElement("li");
tag.innerHTML = '<span class="toggle">Jan</span>';
You can then add it to the document with .appendChild()
wherever you want it to go.
然后,您可以将它添加到文档中,.appendChild()
随心所欲。
回答by Vatev
var li = document.createElement('li');
var span = document.createElement('span');
span.className = 'toggle';
span.appendChild(document.createTextNode('Jan'));
li.appendChild(span);