HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

Finding HTML Elements

To manipulate an HTML element, you must first find it. In JavaScript, there are several ways to select elements from the DOM tree, ranging from simple ID searches to complex CSS selections.


1. Finding by ID

The most common and fastest way to find an HTML element in the DOM is using the element id. If the element is found, the method will return it as an object.

const element = document.getElementById("intro");

2. Finding by Tag Name

Finding elements by their tag name returns an HTMLCollection of matching elements.

const items = document.getElementsByTagName("li");

3. Finding by Class Name

If you want to find all HTML elements with a specific class name, use getElementsByClassName().

const x = document.getElementsByClassName("intro");

4. Finding by CSS Selectors

If you want to find HTML elements that match a specified CSS selector (id, class names, types, attributes, etc.), use the querySelectorAll() method.

const x = document.querySelectorAll("p.intro");

5. Finding by HTML Object Collections

The document object has built-in collections for certain types of elements, like forms.

const form = document.forms["myForm"];
Technical Difference: getElementsBy... methods return a Live HTMLCollection, while querySelectorAll() returns a Static NodeList. This means the NodeList won't update automatically if you add new elements later!

Key Points to Remember

  • IDs should be unique—they return only one element
  • Tag and Class selectors return lists of elements
  • querySelector() returns only the first match
  • querySelectorAll() returns every match as a NodeList
  • Iterate through lists (collections) using a for loop or forEach() (on NodeLists)
  • The document object must exist before calling these methods