简体   繁体   English

到 javascript 数组的 div 列表(没有 jquery)

[英]A list of divs to javascript array (no jquery)

I'm wondering how i can convert a list of html divs into a javascript array?我想知道如何将 html div 列表转换为 javascript 数组? So here is the html code i have所以这是我的html代码

<div class="colors">
    <div>Red</div>
    <div>Blue</div>
    <div>Orange</div>
    <div>Green</div>
</div>

so now i want to convert the divs that is inside the first div to a javascript array.所以现在我想将第一个 div 内的 div 转换为 javascript 数组。 How can i do this?我怎样才能做到这一点?

You can use the document.querySelectorAll and then create an array from them through Array.from method:您可以使用document.querySelectorAll然后通过Array.from方法从它们创建一个数组:

 console.log(Array.from(document.querySelectorAll('.colors div')));
 <div class="colors"> <div>Red</div> <div>Blue</div> <div>Orange</div> <div>Green</div> </div>

Fairly easy to do - convert the NodeList of the divs to an array, then map the innerText :相当容易 - 将 div 的 NodeList 转换为数组,然后映射innerText

 var divArray = Array.prototype.slice.call(document.querySelectorAll(".color div")); divArray = divArray.map(e => e.innerText); console.log(divArray);
 <div class="colors"> <div>Red</div> <div>Blue</div> <div>Orange</div> <div>Green</div> </div>

Or if you want the actual div elements - not their text, eliminate this line:或者,如果您想要实际的 div 元素 - 而不是它们的文本,请删除此行:

divArray = divArray.map(e => e.innerText);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM