使用 JavaScript 对 li 元素重新排序
Re-order li elements with JavaScript
我有一个按字母顺序显示位置的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(',');
相关文章:
- 如何按名称对四方形场地进行排序(即排序
- Javascript排序和排序
- 返回相同排序的排序函数
- JavaScript排序函数排序时不应该排序
- jQuery 表排序器排序不起作用
- 对生成的行进行排序表排序器
- 当值相同时,在忽略排序中排序
- 使用JQuery UI双向排序/未排序拖放
- JavaScript网格按编号排序,排序问题
- 如何使用布局管理器重新排序/排序嵌套视图而不重新渲染
- 任意重新排序和排序对象文字的 JavaScript 数组
- JS对象排序日期排序
- javascript排序和排序等于结果.怎样
- 嵌套可排序新添加的项目不会移动
- 在JavaScript中,在不干扰先前排序(部分排序)的情况下,在另一个键上使用对象数组
- 支持XML数据存储的可编辑网格,具有行编辑/排序/重新排序功能
- 使用AngularJS自定义排序函数排序Email值时出现问题
- Javascript排序函数排序错误
- Dojo增强网格嵌套排序无法排序
- JQuery UI可排序:按排序顺序保存键