0Pricing
JavaScript Academy · Lesson

getElementById and getElementsByClassName

Use classic selection methods.

getElementById

getElementById returns the single element with the matching id, or null. Ids must be unique on a page, so this returns one element.

const header = document.getElementById("header");
console.log(header.tagName);

No Hash Symbol

Unlike CSS selectors, you pass the raw id without the #. Passing "#header" would fail to match.

document.getElementById("menu");   // correct
document.getElementById("#menu");  // wrong, returns null

All lessons in this course

  1. Selecting Elements with querySelector
  2. getElementById and getElementsByClassName
  3. Traversing Parents, Children and Siblings
  4. NodeList vs HTMLCollection
← Back to JavaScript Academy