使用 JavaScript 对 li 元素重新排序

Re-order li elements with JavaScript

本文关键字:排序 新排序 JavaScript li 元素 使用      更新时间:2023-09-26

我有一个按字母顺序显示位置的li,我想抓取列表中的元素并以不同的顺序返回。

    <li class="single-contact-location">
      <span>Location</span> 
     ALocation, BLocation, CLocation, DLocation, ELocation, FLocation
    </li>   

假设 Bocation、ALocation、CLocation、DLocation、ELocation、FLocation

var li = document.getElementsByClassName("single-contact-location")[0];

我得到了li类和带有位置的跨度,但span让我感到困惑,因为我无法抓取和重新排序元素。

可以使用以下代码读取位置列表:

/* 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>

您可以使用

childNode属性来获取这些字段并进行相应的修改。这是一个小提琴 http://jsfiddle.net/sdvowy38/1/

 var li = document.getElementsByClassName("single-contact-location");
 var arr=li[0].childNodes[2].textContent.trim().split(',');