Eyal
Eyal

Reputation: 5848

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?

Upvotes: 52

Views: 87400

Answers (7)

Steven Spungin
Steven Spungin

Reputation: 29109

You can use the createTreeWalker API that is now standard. A regular expression is also a convenient way to check for all levels.

const rx = /^H[1-6]$/
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT)
while (walker.nextNode()) {
  if (rx.test(walker.currentNode.tagName)) {
    // Do your thing here
  }
}

See https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker

The same approach can be used to filter text content, attribute keys and values, etc.

Upvotes: 0

GibboK
GibboK

Reputation: 73918

If you are using jQuery you can use

$(":header")

example from jQuery documentation

<script>$(":header").css({ background:'#CCC', color:'blue' });</script>

Documentation

Upvotes: 22

QuentinUK
QuentinUK

Reputation: 3077

Give them a common class name then use getElementsByClassName

Upvotes: 0

Jan Kyu Peblik
Jan Kyu Peblik

Reputation: 1537

QuentinUK's is the best answer here, as it is the /only/ one that answers the question by providing a solution using only JavaScript with no libraries.

for (i=1; i<=6; i++) {
    var headers = document.getElementsByTagName('h'+i);
    for (j=0; j<headers.length; j++) {
        headers[j].className = 'h';
    }
}
var headers = document.getElementsByClassName('h');
for (i=0; i<headers.length; i++) {
    headers[i].innerHTML += ' '+i;
}

Upvotes: 4

user113716
user113716

Reputation: 322492

If you're just needing some cross-browser DOM selection, there's no need to load jQuery.

Just load Sizzle instead. It's the selector engine that jQuery uses.

Example: http://jsfiddle.net/77bMG/

var headings = Sizzle('h1,h2,h3');

for( var i = 0; i < headings.length; i++ ) {
    document.write('<br>');
    document.write(i + ' is ' + headings[i].innerHTML);
}

Or without any library code, you can walk the DOM, and push the headings into an Array.

Example: http://jsfiddle.net/77bMG/1/

var headings = [];

var tag_names = {
    h1:1,
    h2:1,
    h3:1,
    h4:1,
    h5:1,
    h6:1
};

function walk( root ) {
    if( root.nodeType === 1 && root.nodeName !== 'script' ) {
        if( tag_names.hasOwnProperty(root.nodeName.toLowerCase()) ) {
            headings.push( root );
        } else {
            for( var i = 0; i < root.childNodes.length; i++ ) {
                walk( root.childNodes[i] );
            }
        }
    }
}

walk( document.body );

for( var i = 0; i < headings.length; i++ ) {
    document.write('<br>');
    document.write(i + ' is ' + headings[i].innerHTML);
}

Upvotes: 9

TJHeuvel
TJHeuvel

Reputation: 12608

You dont need jQuery for something simple; try his:

var tags = [ "h1","h2","h3" ];
var all_headings = [];

for(var i = 0; i < tags.length; i++)
    all_headings = all_headings.concat(document.getElementsByTagName(tags[i]));

Upvotes: 3

Alex Turpin
Alex Turpin

Reputation: 47776

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

Upvotes: 88

Related Questions