javascripthtmlgetelementsbytagname

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


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?


Solution

  • 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")