Playwright : Print all the attributes of a dom element

Priyanshu S Avatar

Often, I find it helpful to debug HTML elements while locating them in tests by printing the various attributes they contain on the rendered page. To accomplish this, I use a simple piece of code that prints all the attributes as key-value pairs for the rendered page.

[Read, How to wait for API Response in Selenium WebDriver 4?]

A sample code in Playwright to print all the attributes of an element identified by <locator>.

const elementAttributes = await page.$eval("locator", (el) = >{
const attributes = el.attributes;
const attributeMap = {};
for (let i = 0; i < attributes.length; i++) {
attributeMap[attributes[i].name] = attributes[i].value;
}
return attributeMap;
});

// Print the attributes and their values
console.log("Element Attributes:");
console.log(elementAttributes);


Your subscription encourages me to write more insightful articles.

Subscribe to my newsletter and explore Quality Assurance beyond just manual and automation testing!

We don’t spam! Read our privacy policy for more info.

Thank you for reading this post, don’t forget to subscribe!

Priyanshu S Avatar

Leave a Reply