JavaScript Manipulating Document Elements

Selection

The document object provides several methods for selecting single or multiple nodes by tag name, element id or element class.

Modern selection

The document's querySelector method takes a CSS selector as the first parameter and returns the first HTML element that matches the selector. The querySelectorAll method is similar, but returns all elements that match the query instead.

// gets the first paragraph in the document
const p = document.querySelector("p")
// gets the first element with the class "recipe"
const recipe = document.querySelector(".recipe")
// gets the first element with the id "cake"
const cake = document.querySelector("#cake")

Get elements by tag name

document.getElementsByTagName selects all elements in the document with the specified tag name.

const ps = document.getElementsByTagName("p")

Get elements by class

document.getElementsByClassName selects all elements in the document with the specified class name.

const boxes = document.getElementsByClassName("box")

Get elements by id

document.getElementsById selects all elements in the document with the specified id.

const logo = document.getElementsById("logo")