Home > Web Front-end > JS Tutorial > Obtain CLASS object using native JS (very simple and practical)_javascript skills

Obtain CLASS object using native JS (very simple and practical)_javascript skills

WBOY
Release: 2016-05-16 16:33:52
Original
2204 people have browsed it

I heard it is the most commonly used. . . . I came up with this idea after watching The Art of DOM Programming.

<!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>无标题文档</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();//定义数组 

var classint=0;//定义数组的下标 

var tags=document.getElementsByTagName("*");//获取HTML的所有标签 

for(var i in tags){//对标签进行遍历 

if(tags[i].nodeType==1){//判断节点类型 

if(tags[i].getAttribute("class") == classnames)//判断和需要CLASS名字相同的,并组成一个数组 

{ 

classobj[classint]=tags[i]; 

classint++; 

} 

} 

} 

return classobj;//返回组成的数组 

} 


//以下就是测试了 

var a=getElementsClass("ca"); 

a[0].onclick=function(){alert("我们来了");} 

a[1].innerHTML='我们来了'; 

</script>
Copy after login

Sometimes there are multiple doms with the same class, which can be handled like this:

Copy code The code is as follows:

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

If there are multiple identical classes, they can be used together. If you want to reach JQ, where can you click directly? You also need to do some more complicated processing
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template