Harshil Chovatiya - Day 16: Selecting DOM Elements
In today's lesson, we will explore different methods for selecting DOM elements in JavaScript. Accurate element selection is a crucial step in DOM manipulation, and JavaScript provides several methods to achieve this.
1. getElementById Method:
This method selects an element by its unique id attribute. It's the fastest way to access an
element when you know its id.
Example:
var element = document.getElementById("myDiv");
console.log(element.textContent); // Outputs: "This is a div element."
2. getElementsByClassName Method:
This method selects elements by their CSS class name. It returns a collection (HTMLCollection) of elements with the specified class.
Example:
var elements = document.getElementsByClassName("my-para");
console.log(elements.length); // Outputs: 2
console.log(elements[0].textContent); // Outputs: "Paragraph 1"
console.log(elements[1].textContent); // Outputs: "Paragraph 2"
3. getElementsByTagName Method:
This method selects elements by their HTML tag name. It returns a collection of elements with the specified tag.
Example:
var items = document.getElementsByTagName("li");
console.log(items.length); // Outputs: 2
console.log(items[0].textContent); // Outputs: "Item 1"
console.log(items[1].textContent); // Outputs: "Item 2"
4. querySelector and querySelectorAll Methods:
These methods use CSS-style selectors to select elements. querySelector returns the first
matching element, while querySelectorAll returns a collection of all matching elements.
Example:
var element = document.querySelector(".highlight");
console.log(element.textContent); // Outputs: "Paragraph 1"
var elements = document.querySelectorAll(".container p");
console.log(elements.length); // Outputs: 2
console.log(elements[0].textContent); // Outputs: "Paragraph 1"
console.log(elements[1].textContent); // Outputs: "Paragraph 2"
These methods provide versatile ways to select DOM elements, depending on your specific requirements. As you continue your journey into DOM manipulation, mastering element selection is crucial for building interactive web applications.

Comments
Post a Comment