Skip to content

unicorn/prefer-query-selector Pedantic

🛠️ An auto-fix is available for this rule for some violations.

What it does

Prefer .querySelector() over .getElementById(), .querySelectorAll() over .getElementsByClassName() and .getElementsByTagName().

Example

Examples of incorrect code for this rule:

javascript
document.getElementById("foo");
document.getElementsByClassName("foo bar");
document.getElementsByTagName("main");
document.getElementsByClassName(fn());

Examples of correct code for this rule:

javascript
document.querySelector("#foo");
document.querySelector(".bar");
document.querySelector("main #foo .bar");
document.querySelectorAll(".foo .bar");
document.querySelectorAll("li a");
document.querySelector("li").querySelectorAll("a");

References

Released under the MIT License.