要獲取元素的類,我們要了解元素的類是通過什么添加上的踱侣?因為每個元素都有一個或多個特性粪小,這些特性的用途是給出相應(yīng)元素或其內(nèi)容的附加信息大磺。操作特性的Dom方法有三;分別為:getAttribute()、setAttribute()和removeAttribute()探膊;這三個方法可以針對任何特性使用杠愧,包括那些以HTMLElement類型屬性的形式定義的特性。
html結(jié)構(gòu)
<div>
<p>1</p>
<p class="text">text</p>
<p>2</p>
</div>
js行為代碼
var p=documnet.getElementsByTageName("p") 或者document.querySelectorAll("p");
var len=p.length;
//方法1
for(var i=0;i<len;i++){
if(p[i].getAttribute("class")){
if(p[i].className.indexOf('text') >-1){
console.log(“找到class類”)
}
}
}
//方法2
for(var i=0;i<len;i++){
if(p[i].getAttribute=="text"){
console.log("找到calss類")
}
}
//方法3
for(var i=0突想;i<len;i++){
if(p[i].className=="text"){
console.log(“找到class類”)
}
}