我有一个按字母顺序显示位置的 li,我想获取列表的元素并以不同的顺序返回。
<li class="single-contact-location">
<span>Location</span>
ALocation, BLocation, CLocation, DLocation, ELocation, FLocation
</li>
假设 BLocation、ALocation、CLocation、DLocation、ELocation、FLocation
与
var li = document.getElementsByClassName("single-contact-location")[0];
我得到了 li 类和带有位置的跨度,但跨度让我感到困惑,因为我无法抓取元素并重新排序。
最佳答案
您可以使用以下代码读取位置列表:
/* querySelector: IE8+ support */
var span = document.querySelector(".single-contact-location > span");
/* get the next node after the span */
var textNodeAfterSpan = span.nextSibling;
/* Get the content of the text node and split it */
var locationList = textNodeAfterSpan.nodeValue.split(', ');
/* Reorder it */
var mainLocation = locationList[1];
locationList[1] = locationList[0];
locationList[0] = mainLocation;
/* Rewrite it */
textNodeAfterSpan.nodeValue = ' ' + locationList.join(', ');
<li class="single-contact-location">
<span>Location</span>
ALocation, BLocation, CLocation, DLocation, ELocation, FLocation
</li>
关于javascript - 使用 JavaScript 重新排序 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30915828/