nodeQueryMethods
Prefer modern
querySelectorandquerySelectorAllover legacy DOM query methods.
✅ This rule is included in the browser stylistic preset.
The legacy DOM query methods getElementById, getElementsByClassName, getElementsByTagName, and getElementsByTagNameNS are less flexible and consistent than the modern querySelector and querySelectorAll methods.
The querySelector methods use CSS selectors, which are more powerful, widely understood, and consistent with other web APIs.
Examples
Section titled “Examples”const element = document.getElementById("myId");const elements = document.getElementsByClassName("myClass");const divs = document.getElementsByTagName("div");const elements = document.getElementsByTagNameNS( "http://www.w3.org/1999/xhtml", "div",);const element = document.querySelector("#myId");const elements = document.querySelectorAll(".myClass");const divs = document.querySelectorAll("div");// For namespaced elements, use attribute selectors or specific namespaced query methodsconst svgElements = document.querySelectorAll('svg, [xmlns*="svg"]');Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If your project needs to support very old browsers that don’t have querySelector support (Internet Explorer 7 and below), you might not be able to use this rule. However, querySelector has been widely supported since Internet Explorer 8 and is part of the modern web platform.
Further Reading
Section titled “Further Reading”- MDN: Document.querySelector()
- MDN: Document.querySelectorAll()
- MDN: Element.querySelector()
- MDN: Element.querySelectorAll()
Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
unicorn/prefer-query-selector - Oxlint:
unicorn/prefer-query-selector
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.