Selecting Elements
JavaScript can select HTML elements from a web page using the DOM. Once an element is selected, JavaScript can read its content, modify it, change its style, or respond to user interactions.
What does Selecting Elements mean?
Selecting an element means finding a particular HTML element from the DOM so that JavaScript can work with that element.
Simple Definition
JavaScript uses DOM methods such as getElementById(), getElementsByClassName(), and querySelector() to find HTML elements.
How Element Selection Works
The browser creates a DOM tree from the HTML page. JavaScript can use the document object to select the required element.
Common Element Selection Methods
getElementById()
Selects a single element using its id.
getElementsByClassName()
Selects elements that have a particular class name.
querySelector()
Selects the first element that matches a CSS selector.
Example 1: getElementById()
The getElementById() method selects an HTML element using its id.
const heading =
document.getElementById("title");
console.log(heading);
Selected element: <h1 id="title">JavaScript Tutorial</h1>
Example 2: getElementsByClassName()
The getElementsByClassName() method selects elements using their class name.
const students =
document.getElementsByClassName("student");
console.log(students);
Number of selected elements: 3
Students: Amit, Priya, Rahul
Example 3: querySelector()
The querySelector() method selects the first element that matches a CSS selector.
const message =
document.querySelector(".message");
console.log(message);
Selected element: <p class="message">Welcome to CIIT Training Institute!</p>
Example 4: querySelectorAll()
The querySelectorAll() method selects all elements that match a CSS selector.
const courses =
document.querySelectorAll(".course");
console.log(courses.length);
Number of selected elements: 3
Important Note
The examples above show actual DOM methods used inside a browser. The CIIT JavaScript Compiler is a console-based execution environment, so the Try It buttons send compiler-safe JavaScript representations to the compiler while the tutorial code demonstrates the real DOM API.
Real-World Example
Suppose a training website contains multiple course cards. JavaScript can select those course elements and work with them.
const courses =
document.querySelectorAll(".course");
console.log("Courses Found:", courses.length);
Courses Found: 3
CIIT Training Institute
Summary
JavaScript can select HTML elements through the DOM. getElementById() selects an element by its ID, getElementsByClassName() selects elements by class name, querySelector() selects the first matching element, and querySelectorAll() selects all matching elements.