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

Usage: document.querySelector(query);

This function allows us to select elements based on a selector:

document.querySelector("button"); // searches for the first <button> tag
document.querySelector(".vintage"); // searches for the first tag with the "vintage" class
document.querySelector("#nexus"); // searches for the first tag with the id "nexus"

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);

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