Use Array.prototype.map()
const ids = [...document.querySelectorAll(".class1")].map(el => el.id );
console.log(ids); // ["first", "second"]
Use Array.prototype.map()
const ids = [...document.querySelectorAll(".class1")].map(el => el.id );
console.log(ids); // ["first", "second"]
To create an Array of the id
attribute-values:
// create an Array from the iterable NodeList returned by
// document.querySelectorAll():
Array.from(
// retrieve all elements matching the selector:
document.querySelectorAll('.class1')
// use Array.prototype.map() to return a new array
// based on the existing Array-elements/values:
).map(
// using an Arrow function to return the id of
// each node:
(el)=>this.id
);
One way to solve the problem would be to use document.getElementsByClassName .
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
const elementsWithClass1 = [...document.getElementsByClassName('class1')]
.map(element => element.id);
console.log(elementsWithClass1);
<div id="first" class="class1">...</div>
<div id="second" class="class1">...</div>
<div id="third">...</div>
I know you can check if an element has a class with element.classList.contains(class)
. However, that’s not what I’m looking for – I want to be able to list all elements that have a certain class.
For example, if I have the following:
<div id="first" class="class1">...</div>
<div id="second" class="class1">...</div>
<div id="third">...</div>
What can I use so that I get an output of #first
and #second
? I’d like to avoid checking each and every one using the .classList.contains()
method, as it is rather tedious and inefficient.
I’d prefer an answer using only HTML, CSS, and JavaScript – thank you in advance.