Querying the DOM - Selectors
Querying the DOM involves searching for elements in the html document. This is done by the way of selectors (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
in JS is a global reference to the html document that is the target of the script.
document.querySelector
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
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
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
document.getElementsbyClassName
This returns an array of all the elements that belong to a given class.
Usage: document.getElementsByClassName(className);
document.getElementsByTagName
document.getElementsByTagName
This returns an array of all the elements in the document that have a given tag.
Usage: document.getElementsByTagName(tagName);
Next steps
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.
Last updated