How do I get all h1,h2,h3 etc elements in javascript?

Eyal picture Eyal · Aug 15, 2011 · Viewed 54.3k times · Source

I want to write something like this in javascript:

var all_headings = document.getElementsByTagName("h1,h2,h3,h4,h5,h6");

all_headings would then be a list of all elements that are h1 or h2 or h3... And in the order that they appear in the document, of course.

How do I do it?

Answer

Alex Turpin picture Alex Turpin · Aug 15, 2011

With modern browsers you can do

document.querySelectorAll("h1, h2, h3, h4, h5, h6")

Or you could get cross-browser compatibility by using jQuery:

$("h1, h2, h3, h4, h5, h6")