If you would prefer to watch this post, you can do so with this community resource lesson on egghead.io.
You may not always want to select the first child of an element. document.querySelector will match elements based on a pattern you give it. Say we have a page that looks like this:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Select an Element with document.querySelector</title> </head> <body> <ul> <li>Peanut Butter Falcon</li> <li>Knives Out</li> </ul> </body> </html>
Instead of accessing the first
li element with
firstElementChild you can use
If you guessed
<li>Peanut Butter Falcon</li> you were right. Don't feel bad if you got it wrong though, you weren't supposed to know the answer!
How do we get the element with the inner text of 'Knives out' with
Right now we can't. We need to assign id's to the elements like this:
<ul> <li id="movie-1">Peanut Butter Falcon</li> <li id="movie-2">Knives Out</li> </ul>
Now we can call
document.querySelector('#movie-2') to get our
<li id="movie-2">Knives Out</li> element. The
# is how we tell
querySelector we are looking for an id on an element.
Note that this id should be unique in this DOM tree. You never want to give two elements the same id. This will cause some frustrating bugs!
What are some ways you've used