Concat two nodelists

前端 未结 4 1200
夕颜
夕颜 2021-02-04 02:17

I am trying to concat two nodelists using

var ul   = document.querySelector(\"ul\");
var down = document.getElementsByClassName(\"mobile\")[0];
var ul_child = Ar         


        
相关标签:
4条回答
  • 2021-02-04 02:26

    You can try converting the two NodeList objects to arrays first. Then calling concat on the results:

    // Convert the first list to an array
    var ul_list = document.querySelector("ul"),
        ul_children_array = Array.prototype.slice.call(ul_list.children);
    
    // Convert the second list to an array
    var down_list = document.getElementsByClassName("mobile")[0],
        down_children_array = Array.prototype.slice.call(down_list.children);
    
    var ul_child_array = Array.prototype.concat.call(ul_children_array, down_children_array);
    
    0 讨论(0)
  • 2021-02-04 02:28

    This is a bit of a different approach, but perhaps you could try combining them in your query selector:

    var ul_down   = document.querySelectorAll("ul,.mobile:first-child");
    
    0 讨论(0)
  • 2021-02-04 02:40

    Why don't you use one selector to select them at the same time than you do not need to concat them and you end up with an HTML Collection instead of an Array.

    var elems = document.querySelectorAll("ul > li, .mobile > *");
    console.log(elems);
    <ul><li>x</li></ul>
    <div class="mobile">y</div>

    0 讨论(0)
  • 2021-02-04 02:41

    Set() ensures items are unique and the ES6 Spread operator makes it neat & tidy:

    var elems = new Set([
        ...document.querySelectorAll(query1),
        ...document.querySelectorAll(query2)
    ]);
    
    0 讨论(0)
提交回复
热议问题