javascript - 使用 JavaScript 重新排序 li 元素

标签 javascript html css list

我有一个按字母顺序显示位置的 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/

相关文章:

html - 创建 View 之前使用 html

php - 如何使用中文版 mPDF

css - Bootstrap 跨度换行,不与一行中的其他跨度对齐

javascript - window.onload 和 getelementbyid 返回 null

javascript - Braintree 托管字段未在 Polymer 上渲染

javascript - 从浏览器访问麦克风 - Javascript

Javascript 在第一次完成之前执行第二行代码

html - 为什么颜色属性没有改变?

javascript - 从 grunt-contrib-connect 请求对象获取数据

css - 如何让 flex 元素收缩直到需要包装,然后扩展以填充新空间?