代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul id="liBox">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
<script>
/* 获取父节点 */
let liBox=document.getElementById('liBox');
/* 打印父节点中所有节点 */
console.dir(liBox.childNodes);
/* 创建fragment */
let fragment=document.createDocumentFragment();
/* 循环li里面所有的子节点 */
for(let i=0;i<liBox.childNodes.length;i++){
/* 赋值 */
let child=liBox.childNodes[i];
/* 向fragment里面添加li里的每一项 */
fragment.appendChild(child)
}
/* 死循环,条件为ul里的最后一个子节点 */
while(liBox.firstChild){
fragment.appendChild(liBox.firstChild)
}
/* 将fragment转换成数组并使用map遍历 */
Array.prototype.slice.call(fragment.childNodes).map(nodeltem => {
console.log(nodeltem.nodeType);
/* 如果节点是元素节点,则 nodeType 属性将返回 1 */
if(nodeltem.nodeType===1){
/* 给里面的内容替换 */
nodeltem.innerHTML='替换成功'
}
});
/* 将切割好的只剩li节点的数组添加到ul中 */
liBox.appendChild(fragment);
</script>
</html>
效果如下: