Home > database >  Get last class from div with javascript
Get last class from div with javascript

Time:12-01

Given a div such as <div ></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.

CodePudding user response:

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 >one</div>
<div >two</div>

CodePudding user response:

 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)

CodePudding user response:

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);
  • Related