英文:
How to form an array using series of dataset Id values you've collected from a div
问题
数据集ID已附加到图像 假设我已将数据集ID值附加到一系列div中,这些值彼此不同,如果我想收集这些值并将它们组成一个数组,我该如何做?
我已经尝试通过循环遍历它们,因为它们都是具有相同类名的div,但它只会将值返回到单独的数组中,而不是合并到一个数组中。我不能使用array.from()
,因为它会将字符串分成单独的字符并形成一个包含它们的数组。你们有什么建议?
英文:
The dataset Id is attached to the imageLet's say for instance I've attached dataset Id values to a series of div's and these values are different from one another, if I want to collect these values and form an array with them how do it do it?
I already tried looping through them since they are all divs with the same class name,but it gives me back the values on individual array and not collectively into one array. I can't use array.from() cos it would just turn the string into separate characters and form an array with them. What do you all suggest I do?
答案1
得分: 1
你可以首先使用document.querySelectorAll
按类选择所有元素,然后应用映射函数来读取dataset.id
。
const res = Array.from(document.querySelectorAll('.a'), d => d.dataset.id);
console.log(res);
<div data-id="100" class="a"></div>
<div data-id="101" class="a"></div>
<div data-id="102" class="a"></div>
英文:
You can first select all the elements by class with document.querySelectorAll
, then apply a mapping function to read the dataset.id
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const res = Array.from(document.querySelectorAll('.a'), d => d.dataset.id);
console.log(res);
<!-- language: lang-html -->
<div data-id="100" class="a"></div>
<div data-id="101" class="a"></div>
<div data-id="102" class="a"></div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论