对 DOM 节点进行排序的最简单方法? [英] Easiest way to sort DOM nodes?
本文介绍了对 DOM 节点进行排序的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的列表:
<ul id="mylist">
<li id="list-item1">text 1</li>
<li id="list-item2">text 2</li>
<li id="list-item3">text 3</li>
<li id="list-item4">text 4</li>
</ul>
根据我的喜好重新排列 DOM 节点的最简单方法是什么?(这需要在页面加载时自动发生,列表顺序偏好是从 cookie 中获得的)
What's the easiest way to re-arrange the DOM nodes to my preference? (This needs to happen automatically when the page loads, the list-order preference is gained from a cookie)
例如
<ul id="mylist">
<li id="list-item3">text 3</li>
<li id="list-item4">text 4</li>
<li id="list-item2">text 2</li>
<li id="list-item1">text 1</li>
</ul>
推荐答案
虽然使用 JS 库可能有更简单的方法来做到这一点,但这里有一个使用 vanilla js 的可行解决方案.
Though there's probably an easier way to do this using a JS Library, here's a working solution using vanilla js.
var list = document.getElementById('mylist');
var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
itemsArr.push(items[i]);
}
}
itemsArr.sort(function(a, b) {
return a.innerHTML == b.innerHTML
? 0
: (a.innerHTML > b.innerHTML ? 1 : -1);
});
for (i = 0; i < itemsArr.length; ++i) {
list.appendChild(itemsArr[i]);
}
这篇关于对 DOM 节点进行排序的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文