Lesson 56 +10 XP

Selecting Elements

Selecting Elements

Before you can change an element, you must find it in the DOM.

By id

document.getElementById("demo");

Returns the one element with that id, or null.

By tag name

document.getElementsByTagName("p");

Returns a collection of all <p> elements.

By class name

document.getElementsByClassName("card");

Returns a collection of elements with that class.

By CSS selector

The modern, powerful way:

document.querySelector("#demo");     // first match for a CSS selector
document.querySelectorAll(".card");  // all matches

querySelector vs querySelectorAll

  • querySelector returns the first matching element.
  • querySelectorAll returns all matches as a list.

CSS selectors work

You can use any CSS selector: #id, .class, p, div p, [type="text"].

TL;DR

  • getElementById finds by id.
  • getElementsByTagName and ClassName find collections.
  • querySelector and querySelectorAll use CSS selectors.
  • querySelectorAll is the most flexible.