<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="one"> one </div>
<br>
<h1 class="three">three</h1>
<form class="two" action="">
<i class="two a" id="">two a</i><br>
<b class="two b">two b</b><br>
<b class="two">two</b><br>
<b class="two c">two c</b><br>
<b class="two d a c">two d a c</b><br>
<string class="two e ">two e</string><br>
<a href="javascript:;" class="three h" onclick="getClassNames()">点击获取</a>
</form>
<script>
function getClassName(tag ='', classNames='' ) {
var returnTags=[];
var tags;
if(tag===''){
tags = document.getElementsByTagName("*");
}else {
tags = document.getElementsByTagName(tag);
}
var c=classNames.split('|');
if(c .length===1 && c[0]===''){
alert('类名不能为空');
return false
}
for (var i =0;i<tags.length;i++){
var c1=tags[i].className.split(' ');
if( c .length===1){
//遍历每个标签
c1.forEach(function (v,index) {
if (v === c[0]) {
returnTags.push(tags[i])
}
})
}else {
//遍历每个标签
c1.forEach(function (v,index) {
// 遍历每个需要查询的每个类名
if(!returnTags.includes(tags[i])){
c.forEach(function (value) {
if(!returnTags.includes(tags[i])) {
if (v === value) {
returnTags.push(tags[i]);
}
}
})
}
})
}
}
return returnTags;
}
function getClassNames(){
var tt = prompt('请输入查询的标签,全部标签请用*代替',"*");
var cc = prompt('请输入查询的类名多个用 | 隔开,目前已定义的类名 one two three a b c d e ');
console.log(getClassName(tt, cc));
}
</script>
</body>
</html>