有人问过类似的问题。我希望澄清针对特定场景的最佳解决方案。
我想将所有innerHTML移动到另一个元素。我有:
<div class='mydiv'>
Any HTML could be here. <span></span><div></div> etc..
</div>
并希望将/ prepend / insertAfter / whatever附加到此div:
<div class='myotherdiv'>
Any HTML could be here as well. <span></span><div></div> etc..
</div>
innerHTML +=
等是唯一可行的解决方案吗?或者有没有办法从第一个div移动整个节点列表并将其附加到第二个div?我可以单独抓取每个节点,循环并将它们附加到第二个div - 由于性能原因,我不想要这样做。我在这里寻找一些伏都教魔法,旧的浏览器不需要申请,也没有图书馆。
答案 0 :(得分:4)
可能最有效的方法是使用DocumentFragment
:
// The following assumes the existence of variables div1 and div2
// pointing to the source and destination divs respectively
var frag = document.createDocumentFragment();
var child;
while ( (child = div1.firstChild) ) {
frag.appendChild(child);
}
div2.appendChild(frag);
如果你真的想避开while
循环,那么你可以使用DOM范围的extractContents()
方法(注意:在IE&lt; 9中不支持)。从理论上讲,它可能比以前的方法更有效,因为它减少了脚本调用的DOM调用次数,但我还没有对它进行基准测试。
var range = document.createRange();
range.selectNodeContents(div1);
var frag = range.extractContents();
div2.appendChild(frag);
答案 1 :(得分:0)
var div = document.getElementsByClassName("mydiv"); // this yeilds an array so your going to have to do some sort of looping with it. Unless you assign your div's a id
//since you don't want to loop assuming you assign them id's
//Also avoids looping through the content nodes of your first div
var div_1 = document.getElementById("first_div"); //div to take stuff from
var div_2 = document.getElementById("second_div"); //div your adding to.
var content = div_1.innerHTML; //or innerText if you just want text
//now you have some options
div_2.innerHTML += content; // just add the old content to new div
div_2.appendChild(div_1) // if you want to just put the whole other div into the new div
//if you know whats in your other div, say like a span or a p tag you can use these
div_2.insertBefore("span or p or whatever", content)
div_2.insertAfter(div_2.firstChild, content) //this would insert after the first element inside your second_div