Home >Web Front-end >JS Tutorial >Recommend an encapsulated getElementsByClassName method_javascript skills
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.
for(; i
arr.push(aEle[i]);
}
}
Return arr;
}
}
How to use:
//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.