Home  >  Article  >  Web Front-end  >  Recommend an encapsulated getElementsByClassName method_javascript skills

Recommend an encapsulated getElementsByClassName method_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:29:261155browse

We know that native JS provides us with the getElementsByClassName method, through which we can obtain a collection of nodes containing a specified class. Note that it is a collection, that is, this function returns an array.

However, IE does not support this method, but this method is very practical, so we have to implement such a function specifically for IE.

Copy code The code is as follows:

function getElementsByClassName(oEle,sClass,sEle){
if(oEle.getElementsByClassName){
Return oEle.getElementsByClassName(sClass);
}else{
var aEle=oEle.getElementsByTagName(sEle || '*'),
reg=new RegExp('(^|\s)' sClass '($|\s)'),
arr=[],
i=0,
iLen=aEle.length;

for(; i If(reg.test(aEle[i].className)){
arr.push(aEle[i]);
}
}
Return arr;
}
}

How to use:

Copy code The code is as follows:

//First method: select all div elements with class box_box under the document
getElementsByClassName(document,'box_box','div')[0].style.background='yellow';

//Second option: Select all div elements with class box-box under the document
getElementsByClassName(document,'box-box','div')[0].style.background='yellow';

//The third method: select all classes under the document as box-box elements
getElementsByClassName(document,'box-box')[0].style.background='yellow';

oEle and sClass are required, sEle is optional.

There are no problems with horizontal lines or underlines in sClass, for example: box-box box_box; but if it is other special characters, there may be problems, such as: box$box... Of course, you can add it yourself Customize special characters, such as: box\$box…

Compatibility: Personal test ie6

Friends, you will know after using it yourself. It is super easy to use. Please spread it to other friends.

Statement:
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