Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript中getElementsByClassName的实现 #5

Open
ustccjw opened this issue Oct 19, 2014 · 0 comments
Open

JavaScript中getElementsByClassName的实现 #5

ustccjw opened this issue Oct 19, 2014 · 0 comments
Labels

Comments

@ustccjw
Copy link
Owner

ustccjw commented Oct 19, 2014

JavaScript中getElementsByClassName的实现

原生支持情况

HTML5中添加了getElementsByClassName方法,该方法只接收一个参数,即一个包含一或多个类名的字符串,返回带有指定类的所有元素的NodeList。

var allCurrentUserNames = document.getElementsByClassName('userName current');

IE9+以上和其他现代浏览器均支持。

自己实现

var getElementsByClass = function(searchClass, node, tag) {
    var classElements = new Array();
    if (node == null) {
        node = document;
    }
    if (tag == null) {
        tag = '*';
    }
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

还有基于DOM Tree Walker和XPath的实现方法,在浏览器的兼容性方面可能存在差异。因此理想的方案是:优先使用原生方法 + 配合使用上述的基于DOM的实现方法(IE8以下)。

@ustccjw ustccjw added the blog label Aug 27, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant