Search code examples
javascriptbrowsercss-selectorsselectors-api

Why doesn't querySelector('#id') map to document.getElementById('id')?


I'm into selectors performance lately, and it's bugging me that the browsers which currently implements the Selectors API don't use document.getElementById when a simple #id is being passed.

The performance penalty is huge, so library authors continue to implement their own way around that.

Any ideas?


Solution

  • After making my comment above, I decided to follow through:

    From Node.cpp in the Chromium source

    if (strictParsing && inDocument() && querySelectorList.hasOneSelector() && querySelectorList.first()->m_match == CSSSelector::Id) {
        Element* element = document()->getElementById(querySelectorList.first()->m_value);
        if (element && (isDocumentNode() || element->isDescendantOf(this)) && selectorChecker.checkSelector(querySelectorList.first(), element))
            return element;
        return 0;
    }
    

    So it does map on getElementById, it is just that parsing the string looking for selectors is an expensive operation.