Matt
Matt

Reputation: 1609

Get last class from div with javascript

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

Answers (3)

Carsten Massmann
Carsten Massmann

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

Matt
Matt

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

Robdll
Robdll

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

Related Questions