|
| 1 | +--- |
| 2 | +Title: '.querySelectorAll()' |
| 3 | +Description: 'Returns a static (non-live) NodeList of all elements in the document that match the given CSS selectors.' |
| 4 | +Subjects: |
| 5 | + - 'Code Foundations' |
| 6 | + - 'Web Development' |
| 7 | +Tags: |
| 8 | + - 'Methods' |
| 9 | + - 'Node' |
| 10 | + - 'Selectors' |
| 11 | +CatalogContent: |
| 12 | + - 'introduction-to-javascript' |
| 13 | + - 'paths/front-end-engineer-career-path' |
| 14 | +--- |
| 15 | + |
| 16 | +In JavaScript, the **`.querySelectorAll()`** method under the `document` object returns a static (not live) `NodeList` of all elements that match the given group of [selectors](https://www.codecademy.com/resources/docs/css/selectors). |
| 17 | + |
| 18 | +## Syntax |
| 19 | + |
| 20 | +```pseudo |
| 21 | +document.querySelectorAll(selectors); |
| 22 | +``` |
| 23 | + |
| 24 | +- `selectors`: Represents a string containing one or more CSS selectors used to match elements in the document. It follows the same rules as CSS selectors and can include: |
| 25 | + - Type selectors (`div`, `p`, `span`) |
| 26 | + - Class selectors (`.class-name`) |
| 27 | + - ID selectors (`#id-name`) |
| 28 | + - Attribute selectors (`[type="text"]`, `[disabled]`) |
| 29 | + - Combinations (`div p`, `.container > p`, `ul > li:first-child`) |
| 30 | + |
| 31 | +## Examples |
| 32 | + |
| 33 | +### Example 1 |
| 34 | + |
| 35 | +In this example, a `NodeList` of all `<p>` elements in the document is obtained: |
| 36 | + |
| 37 | +```js |
| 38 | +const matches = document.querySelectorAll('p'); |
| 39 | +``` |
| 40 | + |
| 41 | +### Example 2 |
| 42 | + |
| 43 | +The following example returns a list of all `<div>` elements in the document with a class of either `note` or `alert`: |
| 44 | + |
| 45 | +```js |
| 46 | +const matches = document.querySelectorAll('div.note, div.alert'); |
| 47 | +``` |
| 48 | + |
| 49 | +### Example 3 |
| 50 | + |
| 51 | +In this example, a list of `<p>` elements is obtained, whose immediate parent is a `<div>` with the class `highlighted`, and which are inside a container with the ID `test`: |
| 52 | + |
| 53 | +```js |
| 54 | +const container = document.querySelector('#test'); |
| 55 | +const matches = container.querySelectorAll('div.highlighted > p'); |
| 56 | +``` |
0 commit comments