How to Select an HTML Element Using JavaScript?

Estimated read time 1 min read

In JavaScript, you can select an HTML element using the following methods:

  1. document.getElementById(id) – select an element with a specific id.
  2. document.querySelector(selector) – select the first element that matches a CSS selector.
  3. document.querySelectorAll(selector) – select all elements that match a CSS selector and return them as a NodeList.


// select an element with id "myId"
let element = document.getElementById("myId");

// select the first element with class "myClass"
let element = document.querySelector(".myClass");

// select all elements with class "myClass"
let elements = document.querySelectorAll(".myClass");

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply