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

Optimized qsa function #60

Open
ilyaChuk2004 opened this issue Dec 1, 2022 · 0 comments
Open

Optimized qsa function #60

ilyaChuk2004 opened this issue Dec 1, 2022 · 0 comments

Comments

@ilyaChuk2004
Copy link

querySelector('.#id) в 3 раза медленнее, чем getElementById('id')[0].
querySelector('.class') в 5 раз медленнее, чем getElementsByClassName('class')[0].
querySelectorAll('.class') в 160 раз медленнее, чем getElementsByClassName('class').
querySelector('tag') в 230 раз медленнее, чем чем getElementsByTagName('tag')[0].
querySelectorAll('tag') в 300 раз медленнее, чем чем getElementsByTagName('tag').

Как вам идея переписать постоянно использующуюся функцию $ с использованием getElement....?
Вот как я у себя это реализовал

function qs(selector, el, m) {
    el ??= document
    switch (selector[0]) {
        case '@':
            return typeof m == 'number' ? el.querySelectorAll(selector.slice(1)) : el.querySelector(selector.slice(1))
        case '.':
            return typeof m == 'number' ? el.getElementsByClassName(selector.slice(1)) : el.getElementsByClassName(selector.slice(1))[0]
        case '#':
            return el.getElementById(selector.slice(1))
        default:
            return typeof m == 'number' ? el.getElementsByTagName(selector) : el.getElementsByTagName(selector)[0]
    }
}

Да, бывает, без querySelector не обойтись. Но некоторые случаи, как получение по id и tagName, идеально бы реализовать через getElementBy..

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

No branches or pull requests

1 participant