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

混江龙づ霸主 提交于 2019-12-04 23:51:17

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

If you are using jQuery you can use

$(":header")

example from jQuery documentation

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

Documentation

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);
}

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]));

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;
}

Function without jQuery and document.querySelectorAll

function get_all_h(document) {
    var arr = [];
    if (!document) return arr;
    var all_el = document.getElementsByTagName('*');
    for (var i = 0, n = all_el.length; i < n; i++) {
        if (/^h\d{1}$/gi.test(all_el[i].nodeName)) {
            arr.push(all_el[i]);
        }
    }
    return arr;
}
QuentinUK

Give them a common class name then use getElementsByClassName

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!