Get an HTML element by class in JavaScript
You can target an HTML element with JavaScript by using document.querySelector
. This API is similar to jQuery’s basic $
function.
Using document.querySelector
You can use document.querySelector
to target an element, such as an h1
with a class of title
:
Once you’ve captured that element with a variable, you can query and interact with the HTMLElement
(see MDN for the docs) in a number of ways:
Selecting multiple elements
If you need to select multiple elements, you can use document.querySelectorAll
to get an array of elements:
querySelectorAll
returns a NodeList
, but you can still iterate through it using forEach
, as seen below: