Selecting Elements
- This lesson covers various methods to select HTML elements using JavaScript.
Introduction to DOM Manipulation
DOM stands for Document Object Model.
When a web page loads, the browser converts HTML into a tree-like structure called the DOM.
JavaScript uses the DOM to:Access HTML elements
Modify content
Change styles
Handle events
Create dynamic webpages
Before manipulating any element, we must select it first.
What Does “Selecting Elements” Mean ?
Selecting elements means finding and accessing HTML elements so that JavaScript can:
Read their content
Change their text or HTML
Modify CSS styles
Attach events
In simple words:
You cannot control an element unless you select it.
Why Element Selection Is Important
Without proper selection:
JavaScript cannot find elements
DOM manipulation fails
Code throws errors
Interactivity does not work
Correct element selection ensures:
Precise control
Clean code
Better performance
Common Ways to Select Elements in JavaScript
JavaScript provides multiple methods to select elements:
getElementById()
getElementsByClassName()
getElementsByTagName()
querySelector()
querySelectorAll()
querySelector vs querySelectorAll
Method Selects Returns querySelector() First matching element Single element querySelectorAll() All matching elements NodeList Selecting Elements
Modern JavaScript prefers:
querySelector()
querySelectorAll()
Reason:
CSS-style selectors
More powerful
Cleaner syntax
Syntax of querySelectorAll()
document.querySelectorAll(selector);
selector can be:
Tag name (p)
Class (.box)
ID (#main)
Attribute (input[type="text"])
Combination (div p, .card h3)
querySelectorAll()
What is querySelectorAll() ?
querySelectorAll() selects all elements that match a given CSS selector and returns them as a NodeList.
A NodeList looks like an array, but it is not a real array.
Selecting Multiple Elements Using querySelectorAll()
Returns all matching elements as a NodeList using a CSS selector
<!-- HTML Structure -->
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<p class="text">Paragraph 3</p>
<script>
// Select all elements with class "text"
let elements = document.querySelectorAll(".text");
console.log(elements); // NodeList of all matching elements
</script>
- Selecting Multiple Elements
Store Multiple Elements Using querySelectorAll()
Selects and stores all matching elements into a NodeList
let elements = document.querySelectorAll(".text");
console.log(elements); // NodeList
This selects all paragraphs with class text.
Accessing Elements from NodeList
Access Elements from NodeList Using Index
Retrieves individual elements from NodeList using index positions
let paragraphs = document.querySelectorAll(".text");
console.log(paragraphs[0].innerHTML);
console.log(paragraphs[1].innerHTML);
- Looping Through querySelectorAll()
Working with querySelectorAll() in Different Ways
Demonstrates selecting, looping, and styling multiple elements using various selectors
<!-- HTML Structure -->
<div class="container">
<p class="text">First</p>
<p class="text">Second</p>
</div>
<h2>Heading 1</h2>
<h2>Heading 2</h2>
<input type="text">
<input type="password">
<script>
// Using for loop
let items = document.querySelectorAll(".text");
for (let i = 0; i < items.length; i++) {
items[i].style.color = "blue";
}
// Using forEach() (Recommended)
items.forEach(function (item) {
item.style.fontWeight = "bold";
});
// Selecting by tag name
let headings = document.querySelectorAll("h2");
headings.forEach(function (h) {
h.style.color = "red";
});
// Selecting by ID
let element = document.querySelectorAll("#main");
console.log(element);
// Selecting nested elements
let paras = document.querySelectorAll(".container p");
paras.forEach(p => {
p.style.backgroundColor = "lightgray";
});
// Selecting using attribute selector
let inputs = document.querySelectorAll('input[type="text"]');
console.log(inputs);
</script>
NodeList vs Array
querySelectorAll() returns a NodeList, not an array.
Feature NodeList Array Index access Yes Yes forEach Yes Yes map / filter No Yes
Convert NodeList to Array
Uses Array.from() to transform a NodeList into a real array
let nodes = document.querySelectorAll(".text");
let array = Array.from(nodes);
console.log(array); // real array
Common Mistakes
Forgetting . for class selector
Forgetting # for ID selector
Trying to use array methods directly
Expecting a single element instead of multiple
Not looping through NodeList
Best Practices for Selecting Elements
Use querySelectorAll() for multiple elements
Use meaningful class names
Keep selectors simple and readable
Avoid deeply nested selectors
Always check length before looping
Real-World Use Cases
Styling multiple buttons
Adding events to list items
Validating multiple inputs
Highlighting search results
Building dynamic UI components