2016-05-31 44 views
7

我试图用的毗连2周的NodeLists

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

到Concat的2周的NodeLists但这返回来自UL节点列表中只有两个节点,而忽略其他。什么是最有效的连接两个nodelsits?我想,以避免暴力循环,他们

+0

不能突变节点列表和参数'.concat()'必须是数组让他们被平息成结果。循环出了什么问题? – 2016-05-31 18:20:50

+1

'常量ulChild = Array.from(ul.children).concat(Array.from(down.children));' – ndugger

+0

@ndugger:你所拥有的唯一正确的答案在这里*(或做了,直到War10ck更新)*。 – 2016-05-31 18:30:14

回答

11

你为什么不使用一个选择在同一时间选择他们比你不需要Concat的他们,你最终的HTML集合,而不是一个数组。

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

+1

,它假定只有每个之一,但你需要'> *'在每一个人选择要求获得孩子们,这是问题的目标。 – 2016-05-31 18:25:26

+2

这应该是一个评论,而不是一个答案。 – ndugger

+1

@ndugger仍然连接他们一步。我认为这是一个答案。当然你可以使用数组黑客,但它不是一个HTML收集,可能会或可能不会是一件好事。 – epascarello

5

你可以尝试将两个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); 
+2

您正在切片元素,而不是元素列表。把'.children'切片,然后只使用CONCAT在阵列 – 2016-05-31 18:28:30

+2

@squint良好的渔获物。谢谢。我没有注意到,在我的复制/粘贴。也感谢您的优化建议。 – War10ck

1

的ES6传播运营商使得这个整齐&整洁:

var elems = [ 
    ...document.querySelectorAll(query1), 
    ...document.querySelectorAll(query2) 
];