`. As of now, it's length is `1`.
2. The second scripts runs after the browser meets one more `
`, so it's length is `2`.
```html run
First div
Second div
```
In contrast, `querySelectorAll` returns a *static* collection. It's like a fixed array of elements.
If we use it instead, then both scripts output `1`:
```html run
First div
Second div
```
Now we can easily see the difference. The static collection did not increase after the appearance of a new `div` in the document.
Here we used separate scripts to illustrate how the element addition affects the collection, but any DOM manipulations affect them. Soon we'll see more of them.
## Summary
There are 6 main methods to search for nodes in DOM:
Method |
Searches by... |
Can call on an element? |
Live? |
getElementById |
id |
- |
- |
getElementsByName |
name |
- |
✔ |
getElementsByTagName |
tag or '*' |
✔ |
✔ |
getElementsByClassName |
class |
✔ |
✔ |
querySelector |
CSS-selector |
✔ |
- |
querySelectorAll |
CSS-selector |
✔ |
- |
Please note that methods `getElementById` and `getElementsByName` can only be called in the context of the document: `document.getElementById(...)`. But not on an element: `elem.getElementById(...)` would cause an error.
Other methods can be called on elements too. For instance `elem.querySelectorAll(...)` will search inside `elem` (in the DOM subtree).
Besides that:
- There is `elem.matches(css)` to check if `elem` matches the given CSS selector.
- There is `elem.closest(css)` to look for a nearest ancestor that matches the given CSS-selector. The `elem` itself is also checked.
And let's mention one more method here to check for the child-parent relationship:
- `elemA.contains(elemB)` returns true if `elemB` is inside `elemA` (a descendant of `elemA`) or when `elemA==elemB`.