使用JavaScript重新排序li元素

时间:2015-06-18 12:49:22

标签: 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(&#34;单接触位置&#34;)[0];

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

2 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
/* 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(', ');
&#13;
<li class="single-contact-location">
  <span>Location</span> 
  ALocation, BLocation, CLocation, DLocation, ELocation, FLocation
</li>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用childNode属性来抓取这些字段并进行相应修改。这是一个小提琴http://jsfiddle.net/sdvowy38/1/

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