How do I get the ElementHandle's class name when using Puppeteer?

Going to drop this here since this page is currently first result searching for "elementhandle class name"

From the docs, you should just be able to the following

const el = await page.$('.myElement')
const className = await el.getProperty('className')

// alternatively,
// page.$('.myElement')
//    .then(el => el.getProperty('className'))
//    .then(className => ... )

jimmyjoy's answer is right but this may help others use the elementHandle

  page.$(el) // This grabs the element (returns a elementHandle)
    .then((el) => el.getProperty("className")) // Returns a jsHandle of that property
    .then((cn) => cn.jsonValue()) // This converts the className jsHandle to a space delimitedstring       
    .then((classNameString) => classNameString.split(" ") // Splits into array
    .then((x) => console.log(x)

Which would log an array of classes

Note: when i tried to do a .split on the end of jsonValue() it didn't work as i believe the promise isn't resolved at that point so cn.jsonValue().split(" ") wont work


References

List of properties on elements

Puppeteer docs for ElementHandle


I found a solution that helps in parts, but it was good enough to me. I've got the class name acessing ElementHandle._remoteObject.description. Hope this helps someone.

Tags:

Puppeteer