Getting the CLASS object of of with native JS is simple and useful

  • 2020-03-30 04:07:15
  • OfStack

It is said to be the most commonly used... I came up with it from watching dom programming art.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 

<title> Headless document </title> 

<style> 

.ca{background-color:red; padding:20px;} 

.js{ border:1px solid #00F; padding:10px;} 

</style> 

</head> 


<body> 

<div class="ca"> 

sss 

</div> 

<div class="js" id="as"> 

</div> 

<div class="bd"> 

</div> 

<div class="ca"> 

</div> 

</body> 

</html> 

<script> 

function getElementsClass(classnames){ 
var classobj= new Array();//Define an array

var classint=0;//Defines the index of the array

var tags=document.getElementsByTagName("*");//Gets all tags of HTML

for(var i in tags){//The label is traversed

if(tags[i].nodeType==1){//Judge node type

if(tags[i].getAttribute("class") == classnames)//Determines and requires the same CLASS name and forms an array

{ 

classobj[classint]=tags[i]; 

classint++; 

} 

} 

} 

return classobj;//Returns the composed array

} 


//Here's the test

var a=getElementsClass("ca"); 

a[0].onclick=function(){alert(" Here we come ");} 

a[1].innerHTML=' Here we come '; 

</script>

Sometimes more than one dom class is the same, so you can do this:


var a=getElementsClass("ca") ;
for(var i=0;i<a.length;i++){
(function(i){
alert(a[i])
})(i)
}

If you have more than one same class, you can use it together. If you want to reach JQ, where can you directly. Click also needs to do some complicated processing


Related articles: