Reputation: 1609
Given a div such as <div class="abcd ws-compid rh03 a11y-true"></div>
, I need to be able to find the last class on each div and pull it's value.
I can currently get all the classes with classList, but can't seem to get the last class in the DOMTokenList:
[...document.querySelectorAll('.ws-compid')].map(component => component.classList ? {id: component.innerText, type: component.classList} : null);
The class I need will always be the last one in the array, but options like .last()
don't seem to work.
Upvotes: 0
Views: 117
Reputation: 28196
You can also work with .classList
and turn it into an array:
document.querySelectorAll(".ws-compid").forEach(d=>console.log([...d.classList].at(-1)))
<div class="abcd ws-compid rh03 a11y-true">one</div>
<div class="abcd ws-compid rh03 a12y-false">two</div>
Upvotes: 2
Reputation: 1609
Figured out the solution, since it's actually an object, I needed to use Object.entries()
:
[...document.querySelectorAll('.ws-compid')].map(component => component.classList ? {id: component.innerText, type: Object.entries(component.classList).pop()[1]} : null);
Upvotes: -1
Reputation: 6253
Array.from(
document.getElementsByTagName("div")
).map( i => ({
type: i.className.split(' ').pop(),
id: i.innerText
}))
create an array from all div Elements, them map to their last className (type) and value (id)
consider filtering those empty (not all tag have innerText or classes)
Upvotes: 1