2012-11-07 22 views
1

已经提出了类似问题。我正在寻求澄清特定场景的最佳解决方案。使用append/insertAfter类型函数移动innerHTML,不使用jQuery

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

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

而且要附加/添加/ insertAfter /不管到这个div:

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

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

回答

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 <不支持9)。从理论上讲,它可以比以前的方法更高效,因为它减少了脚本所做的DOM调用次数,但是我没有对它进行基准测试。

var range = document.createRange(); 
range.selectNodeContents(div1); 
var frag = range.extractContents(); 
div2.appendChild(frag); 
+1

+1不错的一个。这里是关于文档片段的一个很好的Resig文章:http://ejohn.org/blog/dom-documentfragments/ – David

+0

+1我甚至没有想到documentFragment – Ryan

+0

这真是太棒了! documentFragment消除了循环中追加的大部分疯狂。我会玩extractContents(),甚至不知道这存在!好的工作先生! –

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