Querying the DOM - Selectors
Last updated
Last updated
Querying the DOM involves searching for elements in the html document. This is done by the way of (remember them?)
There are a few ways to search for elements in an html document using JS. We'll take a look at some of them here.
document.querySelector
Usage: document.querySelector(query);
This function allows us to select elements based on a selector:
As before, selectors can search for tag names, classes or ids. It is important to note that querySelector
returns the first match it finds.
The function takes in a string with the selector as an argument, and returns the element as a Node
object. If there is no element that matches the query, it returns null
.
For the html page we've opened up, navigate to the Browser console and lets run some queries.
document.querySelectorAll
This functions similarly to document.querySelector
but this time returns an array of all the elements that match the query. If there are no matches, it returns an empty array.
Usage: document.querySelectorAll(query);
document.getElementById
This is a specific way to query the DOM for an element with a given id. It takes in a string with the expected id (omit the #
prefix) and return the element if it exists (otherwise it returns null
).
Usage: document.getElementById(id);
document.getElementsbyClassName
This returns an array of all the elements that belong to a given class.
Usage: document.getElementsByClassName(className);
document.getElementsByTagName
This returns an array of all the elements in the document that have a given tag.
Usage: document.getElementsByTagName(tagName);
We'll look at how to access the attributes and other properties of elements in the next section, as well as how we can change them using JS.