Loading...
Loading...

Selecting Elements in JavaScript

In JavaScript, selecting elements is crucial for manipulating the Document Object Model (DOM). This tutorial covers various methods to select HTML elements.

1. Selecting Elements by ID

The getElementById method is used to select an element by its unique ID.

const element = document.getElementById("myElementId");

Example:

<div id="myElementId">Hello World!</div>

Testing:

console.log(element.innerText); // Output: Hello World!

2. Selecting Elements by Class Name

The getElementsByClassName method returns a live HTMLCollection of elements with the specified class name.

const elements = document.getElementsByClassName("myClassName");

Example:

<div class="myClassName">Item 1</div>
<div class="myClassName">Item 2</div>

Testing:

console.log(elements[0].innerText); // Output: Item 1

3. Selecting Elements by Tag Name

The getElementsByTagName method returns a live HTMLCollection of elements with the specified tag name.

const elements = document.getElementsByTagName("div");

Example:

<div>First Div</div>
<div>Second Div</div>

Testing:

console.log(elements.length); // Output: 2

4. Selecting Elements Using Query Selectors

The querySelector and querySelectorAll methods allow you to select elements using CSS selectors.

const singleElement = document.querySelector(".myClass");
const multipleElements = document.querySelectorAll("div.myClass");

Example:

<div class="myClass">Element 1</div>
<div class="myClass">Element 2</div>

Testing:

console.log(singleElement.innerText); // Output: Element 1

5. Modifying Selected Elements

Once elements are selected, you can modify their properties, such as innerText, style, etc.

const element = document.getElementById("myElementId");
element.innerText = "New Text!";
element.style.color = "red";

Conclusion

Selecting elements in JavaScript is essential for DOM manipulation. Understanding these methods allows you to effectively interact with and modify web page content.

0 Interaction
1K Views
Views
36 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home