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?
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>
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;
}
Give them a common class name then use getElementsByClassName
来源:https://stackoverflow.com/questions/7065562/how-do-i-get-all-h1-h2-h3-etc-elements-in-javascript