现在,我们要获取下面html中所有node属性为a1的div
<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title >js根据属性值获取元素</title >
</head >
<body >
<div node="a1">q1</div>
<div node="a2">q2</div>
<div node="a3">q3</div>
<div node="a1">q11</div>
<div node="a2">q12</div>
<div node="a3">q13</div>
<div node="a1">q21</div>
<div node="a2">q22</div>
<div node="a3">q23</div>
</body>
</html>
使用jQuery
$('div[node="a1"]')
使用原生js
function getDom(tagName,name,value){
var selectDom = [];
var dom=document.getElementsByTagName(tagName);
for (var i=0; i<dom.length; i++) {
if(value===dom[i].getAttribute(name)){
selectDom.push(dom[i]);
}
}
return selectDom;
}
getDom('div','node','a1')