Recommend a packaged Getelementsbyclassname method _javascript tips

Source: Internet
Author: User

We know that native JS provides us with a getelementsbyclassname method that can be used to get a set of nodes with a specified class, note a collection, which returns an array of the functions.

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

Copy Code code 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<ilen; i++) {
if (Reg.test (Aele[i].classname)) {
Arr.push (Aele[i]);
}
}
return arr;
}
}

How to use:

Copy Code code as follows:

First: Select all of the DIV elements under document that have class Box_box
Getelementsbyclassname (document, ' Box_box ', ' div ') [0].style.background= ' Yellow ';

Second: Select all of the DIV elements under document that have class Box-box
Getelementsbyclassname (document, ' Box-box ', ' div ') [0].style.background= ' Yellow ';

Third: Select all class under document as Box-box element
Getelementsbyclassname (document, ' Box-box ') [0].style.background= ' Yellow ';

Oele, Sclass is required, Sele is optional.

Sclass in the middle line or the underlined wood has problems, such as: Box-box Box_box, but if it is other special characters are very likely to have problems, such as: Box$box ... Of course you can add escape to handle special characters, such as: box\\ $box ...

Compatibility: Pro-Test ie6+

Small partners to use their own to know, super easy, spread to other small partners.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.