Javascript复制节点并修改HTML

时间:2015-11-10 17:05:50

标签: javascript html

我有一个克隆的节点,如下所示:

var my_ele = document.getElementsByClassName('my-ele')[0].cloneNode(true)

哪些副本:

<div class="my-ele">
    <h1>My Element</h1>
    <p>Some text...</p>
</div>

复制后,如何修改复制节点的HTML?也许添加另一个标题并将段落移到顶部。这在Javascript中是否可以实现?

1 个答案:

答案 0 :(得分:1)

只需使用.innerHTML。

// copy the node
var my_ele = document.getElementsByClassName('my-ele')[0].cloneNode(true);

// set the innerHTML value of the copied node to whatever you want. 
// Here, we're appending a red H1 to the beginning of it.
my_ele.innerHTML = '<h1 style="color:red;">Another Header</h1>' + my_ele.innerHTML;

// append to the dom
document.body.appendChild(my_ele);

实例:http://jsbin.com/tohamuqehe/edit?html,js,console,output

修改

要重新排序元素,您可以进一步将克隆元素分解为其子元素,单独操作它们,然后重新附加到克隆元素。示例:http://jsbin.com/buvocajisu/edit?html,js,console,output