Skip to content

nodeQueryMethods

Prefer modern querySelector and querySelectorAll over 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.

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",
);

This rule is not configurable.

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.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.