JavaScript Quick Tip: Query all headings on a page h1-h6
- Updated:
In the jQuery days, we had a fake pseudo selector named ‘:header’ that allowed you to select all h1 to h6 headers on a page. I used this method for example to create a dynamic table of contents code snippet.
CSS does not support this pseudo selector, but here is what you can write instead.
const headerTags = "h1,h2,h3,h4,h5,h6";
let allHeadings = document.querySelectorAll(headerTags);
console.debug(allHeadings);
This code works because you can query multiple selectors in a comma-separated list.

You can also use this code to select multiple CSS classes at once.
See more on the Mozilla Development Network.