使用附加/插入器类型功能移动InnerHTML,无jQuery



已经提出了类似的问题。我希望阐明特定方案的最佳解决方案。

我想将所有InnerHTML移至另一个元素。我有:

<div class='mydiv'>
    Any HTML could be here. <span></span><div></div> etc..
</div>

,想要附加/prepend/insertafter/with to此div:

<div class='myotherdiv'>
    Any HTML could be here as well. <span></span><div></div> etc..
</div>

innerHTML +=和唯一可行的解决方案是吗?还是有某种方法可以将整个节点列表从第一个Div移动并将其附加到第二个DIV?我可以单独捕获每个节点,循环并将它们附加到第二个div -i 出于绩效原因,不想这样做。我在这里寻找一些伏都教魔术,旧浏览器不需要应用,也不需要库。

可能最有效的方法是使用 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);
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

最新更新