Let's say you want to list all of the elements on a page that are absolutely positioned. Or maybe you want to find all of the elements that use CSS grid. How would you do that?
One way is to run a few lines of JavaScript code in the Console tool to iterate over all of the elements and check their computed styles. Here's how:
-
Open the Console tool.
-
Copy the below code snippet and paste it in the Console. Change the
whatToFind
object to match your needs.
var whatToFind = {
property: "position",
values: ["absolute"]
};
var walker = document.createTreeWalker(
document.documentElement,
NodeFilter.SHOW_ELEMENT,
el => {
const style = getComputedStyle(el)[whatToFind.property];
return whatToFind.values.includes(style)
? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_SKIP;
}
);
while (walker.nextNode()) {
console.log(walker.currentNode);
}
- Press Enter and voila! In the screenshot below, all of the absolutely positioned elements on the page are listed.
- If you wanted to find all of the elements that use CSS grid, you would change the
whatToFind
object to this:
var whatToFind = {
property: "display",
values: ["grid", "inline-grid"]
};
To avoid having to copy or type this code every time, you can also use the Snippet tool in Chromium-based browsers as explained in Re-use scripts as snippets.