1

有人问过类似的问题。我正在寻找针对特定场景的最佳解决方案。

我想将所有 innerHTML 移动到另一个元素。我有:

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

并希望在此 div 中附加/前置/插入/插入任何内容:

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

innerHTML +=唯一可行的解​​决方案吗?或者有什么方法可以将整个节点列表从第一个 div 移动并将其附加到第二个 div?我可以单独抓取每个节点,循环并将它们附加到第二个 div -出于性能原因,我不想这样做我在这里寻找一些巫术魔法,旧的浏览器不需要应用,也没有库,拜托。

4

2 回答 2

4

可能最有效的方法是使用 a 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循环,那么你可以使用extractContents()DOM Range 的方法(注意:IE < 9 不支持)。从理论上讲,它可能比以前的方法更有效,因为它减少了脚本进行的 DOM 调用的数量,但我还没有对其进行基准测试。

var range = document.createRange();
range.selectNodeContents(div1);
var frag = range.extractContents();
div2.appendChild(frag);
于 2012-11-07T15:41:41.843 回答
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
于 2012-11-07T15:46:37.550 回答