题目
将ul
下的节点进行翻转
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
let ele = document.querySelector('ul')
function reverseChildrenNodes (ele) {
// todo
}
reverseChildrenNodes(ele)
方案1
let children = Array.from(ele.childNodes)
for (const child of children) {
ele.removeChild(child)
}
children.reverse()
for (const child of children) {
ele.appendChild(child)
}
方案2
let len = ele.childNodes.length
while (len-- > 0) {
// 原节点会被自动移除
ele.appendChild(ele.childNodes[len])
}
方案3
let range = new Range()
range.selectNodeContents(ele)
let fragment = range.extractContents()
let len = fragment.childNodes.length
while (len-- > 0) {
fragment.appendChild(fragment.childNodes[len])
}
ele.appendChild(fragment)
评论
还没有任何评论,你来说两句吧!