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

[js] 第190天 用原生js实现类似getElementsByClassName的方法,不能使用querySelectorAll #1430

Open
haizhilin2013 opened this issue Oct 22, 2019 · 3 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第190天 用原生js实现类似getElementsByClassName的方法,不能使用querySelectorAll

@haizhilin2013 haizhilin2013 added the js JavaScript label Oct 22, 2019
@Evansy
Copy link

Evansy commented Oct 23, 2019

function getElementsByClassName(className)
    const tags = document.getElementsByTagName('*');
    const tempTags = [];
    for(let i=0, len = tags.length; i< len; i++)
    {
        let tag = tags[i];
        tag.classList.contains(className) && tempTags.push(tag)
    }
    return tempTags;
}

@ZhaoHongzcyh
Copy link

实现的方式有很多种,楼上用了document.getElementsByTagName, 那我这里就用document.all

@xudihui
Copy link

xudihui commented Nov 1, 2019

//正则实现

function getElementsByClassName(className){
    const tags = document.getElementsByTagName('*');
    const reg = new RegExp("\\b" + className + "\\b");
    const tempTags = [];
    for(let i=0, len = tags.length; i< len; i++)
    {
        let tag = tags[i];
        reg.test(tag.className) && tempTags.push(tag)
    }
    return tempTags;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

4 participants