I need to get an array of all element ID's of elements of a given class (eg "main-menu-item"). This is what I have so far:
Array.prototype.map.call(document.querySelectorAll(".main-menu-item"), (elem => elem.id));
Is there a cleaner and/or more concise way to do this?
Use the spread operator:
[...document.querySelectorAll(".main-menu-item")].map(elem => elem.id)
You can use Array.from()
with the mapping function, allowing you to convert the NodeList into an array while also specifying how each element should be transformed:
const res = Array.from(document.querySelectorAll(".main-menu-item"), ({id}) => id); console.log(res);
<p class="main-menu-item" id="1">one</p> <p class="main-menu-item" id="2">two</p> <p class="main-menu-item" id="3">three</p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.