3.2 Manipulating HTML Elements

Accessing Elements

To manipulate our HTML elements, we need to access them first. For example, we can access elements by id with getElementById():

const element = document.getElementById(“navbar”);

In general, we can also retrieve elements by:

To access elements by tag name, use getElementsByTagName():

document.getElementsByTagName(“p”);

To access elements by class name, use getElementsByClassName():

document.getElementsByClassName(“text”);

To access elements by CSS selectors, we need to use querySelectorAll():

document.querySelectorAll(“h1.title”);

Here, queryAllSelectors() takes a string as the argument. It finds all elements with a CSS selector (id, class name, tag name, attributes, etc.) matching the argument (review CSS if you’ve gotten unfamiliar with selectors).

For instance, in the above example, “h1.title” is the CSS selector for all h1 tags with “title” as their class attribute. Hence, the above code will retrieve all h1 elements with class “title”.

A number of HTML objects (and object collections) can be accessed directly from document:

document.images[“beach”];