Thuta Learning
IntermediateProgrammingbeginner

DOM Selectors

Relax. We'll talk through this in plain words — no textbook voice.

There are several ways to select HTML elements with JavaScript.

document.getElementById('id'): select a single element by its id

document.getElementsByTagName('p'): select all elements by tag name

document.querySelector('.class'): select the first element that matches a CSS selector

document.querySelectorAll('p.intro'): select all elements that match

javascript
// Assume HTML:
// <div id="main">
//   <p class="content">First paragraph.</p>
//   <p class="content">Second paragraph.</p>
// </div>

const mainDiv = document.getElementById("main");
const firstParagraph = document.querySelector(".content");

console.log("This example needs an HTML page to run.");
// console.log(mainDiv.tagName);
// console.log(firstParagraph.innerText);
You should see
This example needs an HTML page to run.
DOM Selectors | Thuta Learning