How to get all H1, H2, H3, H4 in JS

Into may 2021-09-15 10:27:08

1、 Browser support querySelectorAll

document.querySelectorAll("h1, h2, h3, h4")
 Copy code 

If it is jQuery

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

2、JQuery

var tags = [ "h1","h2","h3","h4" ];
var h_all = [];
for(var i = 0; i < tags.length; i++){
h_all = h_all.concat(document.getElementsByTagName(tags[i]));
}
 Copy code 

3、 pure JS Solution

for (i=1; i<=4; i++) {
var headers = document.getElementsByTagName('h'+i);
for (j=0; j<headers.length; j++) {
headers[j].className = 'h—class';
}
}
var hClass = document.getElementsByClassName('h—class');
for (i=0; i<hClass.length; i++) {
hClass[i].innerHTML += ' '+i;
}
 Copy code 

4、 No, JQuery and querySelectorAll function

function getAllH(document) {
var arr = [];
if (!document) return arr;
var elementAll = document.getElementsByTagName('*');
for (var i = 0, n = elementAll.length; i < n; i++) {
if (/^h\d{1}$/gi.test(elementAll[i].nodeName)) {
arr.push(elementAll[i]);
}
}
return arr;
}
 Copy code 
Please bring the original link to reprint ,thank
Similar articles

2021-09-15

2021-09-15

2021-09-15

2021-09-15