---
title: "unicorn/prefer-query-selector"
description: "Require `querySelector()` and `querySelectorAll()` instead of the `getElement...` methods"
# Generated by src/codegen/lint-rule-docs.ts. Do not edit below this line.
plugin: "unicorn"
aliases: []
kind: "suggestion"
category: "pedantic"
default: "off"
fixable: "yes"
typeAware: false
deprecated: false
---

`getElementById`, `getElementsByClassName`, `getElementsByTagName` and `getElementsByName` each find elements in one way. `querySelector()` and `querySelectorAll()` take any CSS selector, so a lookup can grow from `.item` to `.item:not(.hidden)` without changing the method.

`--fix` rewrites the call when the argument is a string or a template literal without `${}`. It also handles a plain variable, but only for `getElementById`, where `getElementById(id)` becomes `` querySelector(`#${id}`) ``. Other calls are reported and left as they are.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"unicorn/prefer-query-selector" = "error" # or "warn"
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 4} */}
```js
const menu = document.getElementById("menu");
const items = menu.getElementsByClassName("item active");
const links = menu.getElementsByTagName("a");
const emails = document.getElementsByName("email");
```

Not reported:

{/* good */}
```js
const menu = document.querySelector("#menu");
const items = menu.querySelectorAll(".item.active");
const links = menu.querySelectorAll("a");
const emails = document.querySelectorAll("[name='email']");
```

## When not to use it

The results aren't quite the same. The `getElementsBy...` methods return a live collection that follows the document, and `querySelectorAll()` returns a list that doesn't change. An id also isn't always a valid selector. `getElementById("1.a")` works, but `querySelector("#1.a")` throws unless you pass the id through `CSS.escape()`.
