JavaScript DOM Selectors – Get HTML Elements


DOM selectors allow you to access and manipulate HTML elements using JavaScript. They are the foundation for DOM manipulation, styling, and event handling.



1. getElementById() – Select by ID

Returns the element with the specified id.

Example:

<p id="demo">Hello!</p>
<script>
const element = document.getElementById("demo");
console.log(element.textContent); // Output: Hello!
</script>


2. getElementsByClassName() – Select by Class

Returns a live HTMLCollection of all elements with the given class name.

<p class="note">Note 1</p>
<p class="note">Note 2</p>

<script>
const notes = document.getElementsByClassName("note");
console.log(notes[0].textContent); // Output: Note 1
</script>


3. getElementsByTagName() – Select by Tag

Returns a live collection of all elements with the given tag name.

const paragraphs = document.getElementsByTagName("p");


4. querySelector() – Select the First Matching Element

Accepts any valid CSS selector.

<div class="box"></div>
<script>
const box = document.querySelector(".box");
</script>

You can use #id, .class, tag, or even complex selectors.



5. querySelectorAll() – Select All Matching Elements

Returns a NodeList (static, not live) of all matches.

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>
<script>
const items = document.querySelectorAll("ul li");
items.forEach(item => console.log(item.textContent));
</script>


6. Summary Table of DOM Selectors

Selector Method Returns Type
getElementById() Single element Element
getElementsByClassName() All elements with class HTMLCollection
getElementsByTagName() All elements with tag HTMLCollection
querySelector() First match (CSS selector) Element
querySelectorAll() All matches (CSS selector) NodeList


Real-World Use Cases

  • Grabbing form fields (input, textarea)
  • Getting buttons, divs, modals, tabs, etc.
  • Adding dynamic behavior to specific elements
  • Applying styles or event listeners