封装getByClass

方法一:(普通版),获取单一的class:

function getByClass(oParent, sClass) {
    var aResult = [];
    var aEle = oParent.getElementsByTagName('*');
    for (var i = 0; i < aEle.length; i++) {
        // 当className相等时添加到数组中 
        // aEle[i].className.search(sClass)!=-1
        // aEle[i].className.indexof(sClass)!=-1
        if (aEle[i].className == sClass) {
            aResult.push(aEle[i]);
        }
    }
    return aResult;
};

 

方法二(多个class获取—>正则表达式):

function getByClass(oParent,sClass) {
    var aResult = [];
    var aEle = oParent.getElementsByTagName('*');
    var re = new RegExp('\\b' + sClass + '\\b', 'i')
    for (var i = 0; i < aEle.length; i++) {
        if (re.test(aEle[i].className)) {
            aResult.push(aEle[i]);
        }
    }
    return aResult;
};

方法三(多个class获取—>数组):

function getByClass(oParent,sClass) {
    var aResult = [];
    var aEle = oParent.getElementsByTagName('*');
    for (var i = 0; i < aEle.length; i++) {
        var arr = aEle[i].className.split(/\s+/);
        for (var j = 0; j < arr.length; j++) {
            if (arr[j] == sClass) {
                aResult.push(aEle[i])
            }
        }
    }
    return aResult;
};

 

posted @ 2016-03-02 11:15  Jone_chen  阅读(533)  评论(0编辑  收藏  举报