Javascript

Exploring JavaScript Selectors

Exploring JavaScript Selectors: How to Access Elements on a Webpage

JavaScript lets you select and interact with HTML elements — like paragraphs, buttons, divs — using selectors. Think of selectors as ways to find exactly the element(s) you want to work with in the page.


Why Are Selectors Important?

To change content, styles, or respond to user actions, your JavaScript needs to first select the element(s) it should work with.


Common JavaScript Selectors

  1. document.getElementById()

  • Selects a single element by its unique ID.

html
<p id="message">Hello!</p>

<script>
const messageEl = document.getElementById('message');
messageEl.textContent = "Hello, JavaScript!";
</script>


  1. document.getElementsByClassName()

  • Selects all elements with a given class name.

  • Returns a live HTMLCollection (like an array but not quite).

html
<div class="box">Box 1</div>
<div class="box">Box 2</div>

<script>
const boxes = document.getElementsByClassName('box');
for(let box of boxes) {
box.style.color = 'blue';
}
</script>


  1. document.getElementsByTagName()

  • Selects all elements with a specific tag name.

html
<p>Para 1</p>
<p>Para 2</p>

<script>
const paragraphs = document.getElementsByTagName('p');
paragraphs[0].style.fontWeight = 'bold';
</script>


  1. document.querySelector()

  • Selects the first element that matches a CSS selector.

html
<div class="container">
<p class="text">First paragraph</p>
<p class="text">Second paragraph</p>
</div>

<script>
const firstText = document.querySelector('.text');
firstText.style.color = 'red'; // Only the first paragraph changes color
</script>


  1. document.querySelectorAll()

  • Selects all elements that match a CSS selector.

  • Returns a static NodeList, which you can loop through.

html
<p class="text">Para 1</p>
<p class="text">Para 2</p>

<script>
const allTexts = document.querySelectorAll('.text');
allTexts.forEach(p => p.style.fontStyle = 'italic');
</script>


Summary Table

Selector Method Selects Returns Type Notes
getElementById(id) One element by ID Single HTMLElement Fastest, IDs should be unique
getElementsByClassName Elements by class name HTMLCollection Live (updates with DOM changes)
getElementsByTagName Elements by tag name (e.g. ‘p’) HTMLCollection Live collection
querySelector First element matching selector Single Element CSS selector syntax
querySelectorAll All elements matching selector NodeList Static list, supports CSS selectors

Tips:

  • Use querySelector/querySelectorAll for powerful CSS-style selectors.

  • Use getElementById for a single unique element (best performance).

  • Remember to check if your selection returns null (no match) before using it.

Leave a Reply

Your email address will not be published. Required fields are marked *