Concat有两个节点列表

Dar*_*lyn 14 javascript

我试图使用连接两个节点列表

var ul   = document.querySelector("ul");
var down = document.getElementsByClassName("mobile")[0];
var ul_child = Array.prototype.concat.call(ul.children,down.children);
Run Code Online (Sandbox Code Playgroud)

但是这只返回ul nodelist中的两个节点而忽略其他节点.连接两个nodelsits最有效的是什么?我想避免粗暴地循环它们

epa*_*llo 27

为什么不使用一个选择器同时选择它们而不需要连接它们,最终得到的是HTML Collection而不是Array.

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

  • 这应该是评论,而不是答案. (5认同)
  • 这假设每个中只有一个,尽管你需要在每个选择器中使用`>*`来获得孩子,这是问题的目标. (2认同)
  • @ndugger 仍然一步将它们连接起来。我认为这是一个答案。当然你可以使用数组 hack,但是它不是一个 HTML Collection,这可能是也可能不是一件好事。 (2认同)
  • `Array.from` 不是一个数组 hack,我想不出一个合理的论据来解释为什么将其保留为 NodeList 是有益的。 (2认同)

Nei*_*eil 20

ES6 Spread运算符使这个整洁有序:

var elems = [
    ...document.querySelectorAll(query1),
    ...document.querySelectorAll(query2)
];
Run Code Online (Sandbox Code Playgroud)


War*_*0ck 6

您可以尝试首先将两个NodeList对象转换为数组.然后调用concat结果:

// 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);
Run Code Online (Sandbox Code Playgroud)

  • 你正在切片元素,而不是元素列表.将`.children`放在切片中,然后在数组上使用concat (3认同)
  • @squint好抓.谢谢.我没有注意到我的复制/粘贴.还要感谢优化建议. (2认同)

小智 5

这是一种不同的方法,但也许您可以尝试在查询选择器中组合它们:

var ul_down   = document.querySelectorAll("ul,.mobile:first-child");
Run Code Online (Sandbox Code Playgroud)