今天想实现jQuery的unwrap效果,换言之,就是用其孩子把其父节点干掉。为了效率,用到文档碎片,而取孩子时使用到childNodes(返回一个nodeList)
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta content="IE=8" http-equiv="X-UA-Compatible"/> <title>节点集合 by 司徒正美 </title> <style> #aaa { padding:10px; border:1px solid red; } p { border:1px solid blue; } </style> <script type="text/javascript"> window.onload = function(){ var d = document.createDocumentFragment(); var div = document.getElementById("aaa"); var c = div.childNodes; for(var i=0,n=c.length;i<n;i++){ alert(c[i] + " "+ i) d.appendChild(c[i]) } div.parentNode.replaceChild(d,div) } </script> </head> <body> <div id="aaa"> <p class="aaaa">司徒正美</p> <p class="aaaa">司徒正美</p> <p class="aaaa">司徒正美</p> <p class="aaaa">司徒正美</p> <p class="aaaa">司徒正美</p> </div> </body> </html>
如果预先将nodeList转换为数组就没有问题!
window.onload = function(){ var d = document.createDocumentFragment(); var div = document.getElementById("aaa"); var c = div.childNodes; var arr = []; for(var i=0,n=c.length;i<n;i++){ arr.push(c[i]) } for(var i=0,n=arr.length;i<n;i++){ alert(arr[i] + " "+ i) d.appendChild(arr[i]) } div.parentNode.replaceChild(d,div) }