【问题标题】:Sort DOM elements by Specific Child (no JQuery)按特定子项对 DOM 元素进行排序(无 JQuery)
【发布时间】:2016-08-05 12:07:17
【问题描述】:

我特别想对这个 nodeList 进行排序:

var liList = document.getElementsById("theOl").querySelectorAll(".theOl > li");

并按特定的孩子排序:

liList[someIndex].querySelectorAll('a[href]')[0]

基本上,按照 querySelectorAll('a[src]') 返回的 a 的 src 按字母顺序对整个节点列表进行排序。数组中的每个项目都会有这个元素。它总是返回 1 个元素。

【问题讨论】:

  • 我认为你应该为 'a[href]' 排序?
  • 当然不好意思哈哈....其实是另外一个属性,不过里面包含了一些识别信息,所以想都没想就改了!

标签: javascript arrays sorting dom selectors-api


【解决方案1】:

假设您有一个数组数组,并且您希望将它们排序为第一项,这样做。

var arr = [[7,2],[3,4],[8,5],[4,5],[2,4],[1,2]],
    res = arr.sort((p,c) => p[0]<=c[0] ? -1:1);

在您的情况下,如果它是您想要排序的 a 元素的 href 属性,您可能必须执行以下操作。或者,如果您想对里面的文本进行排序,您可以将href 替换为innerTextfirstChild.nodeValue

Array.prototype.sort.call(liList, (p,c) => p.querySelector('a').href <= c.querySelector('a').href ? -1 : 1);

【讨论】:

    【解决方案2】:
    Array.prototype.sort.call(liList[someIndex].querySelectorAll('a[href]'), function (a, b) {
            if (a > b) {
                return 1;
            }
            if (a < b) {
                return -1;
            }
            return 0;
        });
    

    以上代码应根据 li 标签内锚点的 href 元素对元素进行排序。但是,您必须注意它不会按照您期望的顺序替换您的元素,除非您根据排序编写代码来替换。

    【讨论】:

      【解决方案3】:

      这可能不是最有效的,但我开始工作了。

      • querySelectorAll()&lt;a&gt;收集到一个NodeList中

      • Array.prototype.map.call()将NodeList转换成数组

      • map 的数组有一个函数,每个href

      • 接下来填充hrefs 的新数组。

      • 最后按sort()字母排序

      片段

      <!doctype html>
      <html>
      
      <head>
        <meta charset="utf-8">
        <title>36614594</title>
      </head>
      
      <body>
        <ol>
          <li><a href="http://google.com/">Google</a>
          </li>
          <li><a href="https://developer.mozilla.org/en-US/docs/Web/">MDN</a>
          </li>
          <li><a href="http://yahoo.com/">Yahoo</a>
          </li>
          <li><a href="http://msn.com/">MSN</a>
          </li>
          <li><a href="http://att.net/">AT&amp;T</a>
          </li>
          <li><a href="http://stackoverflow.com/">StackOverflow</a>
          </li>
        </ol>
        <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
        <script>
          var linkArray = [];
          var anchorList = document.querySelectorAll('a');
          var anchorArray = Array.prototype.map.call(anchorList, function(obj) {
            var xHref = obj.href;
            return linkSort(linkArray, xHref);
          });
      
          function linkSort(list, obj) {
      
            list.unshift(obj);
            list.sort();
            return list;
          }
          console.log(linkArray);
        </script>
      </body>
      
      </html>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多