Header Ads Widget

Responsive Advertisement

Ticker

6/recent/ticker-posts

DOM | Selecting Elements | Modifying Content | Event Handling | Event Listeners Examples #javascript

Certainly! Selecting elements and modifying their content using JavaScript is a fundamental aspect of working with the DOM (Document Object Model). Here's a step-by-step guide with examples to help you understand how to achieve this.

Selecting Elements

JavaScript provides several methods to select DOM elements:

  1. getElementById(): Selects an element by its unique ID.
  2. getElementsByClassName(): Selects elements by their class name.
  3. getElementsByTagName(): Selects elements by their tag name.
  4. querySelector(): Selects the first element that matches a CSS selector.
  5. querySelectorAll(): Selects all elements that match a CSS selector.

Modifying Content

Once you've selected elements, you can modify their content using properties like:

  • textContent: Sets or gets the text content of an element.
  • innerHTML: Sets or gets the HTML content of an element.
  • value: Sets or gets the value of input elements.

Example

Let's create an example that demonstrates how to select and modify elements using JavaScript.

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM Manipulation Example</title>
</head>
<body>
    <h1 id="main-heading">Original Heading</h1>
    <p class="description">This is a paragraph.</p>
    <button id="change-text-button">Change Text</button>
    <input type="text" id="user-input" value="Type something here">

    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

// 1. Selecting elements
const heading = document.getElementById('main-heading');
const paragraph = document.querySelector('.description');
const button = document.getElementById('change-text-button');
const userInput = document.getElementById('user-input');

// 2. Modifying content
// Change the text content of the heading
heading.textContent = 'Updated Heading';

// Change the inner HTML of the paragraph
paragraph.innerHTML = '<strong>This is an updated paragraph with bold text.</strong>';

// Add an event listener to the button
button.addEventListener('click', () => {
    // Change the value of the input field
    userInput.value = 'Text updated on button click!';
});

Explanation

  1. Selecting Elements:

    • document.getElementById('main-heading') selects the <h1> element with the ID main-heading.
    • document.querySelector('.description') selects the first element with the class description.
    • document.getElementById('change-text-button') selects the <button> element with the ID change-text-button.
    • document.getElementById('user-input') selects the <input> element with the ID user-input.
  2. Modifying Content:

    • heading.textContent = 'Updated Heading'; changes the text content of the heading element.
    • paragraph.innerHTML = '<strong>This is an updated paragraph with bold text.</strong>'; updates the HTML content inside the paragraph element.
    • userInput.value = 'Text updated on button click!'; updates the value of the input field when the button is clicked.
  3. Event Handling:

    • An event listener is added to the button so that when it's clicked, the value of the input field is updated.

Running the Example

  1. Save the HTML content in a file named index.html and the JavaScript content in a file named script.js in the same directory.
  2. Open index.html in a web browser.
  3. Click the button to see the changes in the input field.

This example demonstrates basic DOM manipulation techniques for selecting and modifying elements using JavaScript.

Using getElementsByClassName()

The getElementsByClassName() method returns a live HTMLCollection of elements with the specified class name. Since it returns a collection, you need to iterate over it if you want to modify multiple elements.

HTML Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>getElementsByClassName Example</title>
</head>
<body>
    <h1 class="title">Title 1</h1>
    <h1 class="title">Title 2</h1>
    <h1 class="title">Title 3</h1>
    <button id="change-titles">Change Titles</button>

    <script src="script.js"></script>
</body>
</html>

JavaScript Example (script.js)

// Select all elements with the class name 'title'
const titles = document.getElementsByClassName('title');

// Modify the text content of each element in the collection
const changeTitlesButton = document.getElementById('change-titles');
changeTitlesButton.addEventListener('click', () => {
    for (let i = 0; i < titles.length; i++) {
        titles[i].textContent = 'Updated Title ' + (i + 1);
    }
});

Using getElementsByTagName()

The getElementsByTagName() method returns a live HTMLCollection of elements with the specified tag name. Like getElementsByClassName(), it returns a collection, so you'll need to iterate over it to modify multiple elements.

HTML Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>getElementsByTagName Example</title>
</head>
<body>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <button id="change-paragraphs">Change Paragraphs</button>

    <script src="script.js"></script>
</body>
</html>

JavaScript Example (script.js)

// Select all <p> elements
const paragraphs = document.getElementsByTagName('p');

// Modify the text content of each paragraph element in the collection
const changeParagraphsButton = document.getElementById('change-paragraphs');
changeParagraphsButton.addEventListener('click', () => {
    for (let i = 0; i < paragraphs.length; i++) {
        paragraphs[i].textContent = 'Updated Paragraph ' + (i + 1);
    }
});

Explanation

  1. getElementsByClassName():

    • document.getElementsByClassName('title') selects all elements with the class name title.
    • titles[i].textContent = 'Updated Title ' + (i + 1); updates the text content of each element in the collection when the button is clicked.
  2. getElementsByTagName():

    • document.getElementsByTagName('p') selects all <p> elements.
    • paragraphs[i].textContent = 'Updated Paragraph ' + (i + 1); updates the text content of each paragraph when the button is clicked.

In both cases, clicking the respective buttons will update the content of the elements selected by their class name or tag name.


Handling events and event listeners in JavaScript is essential for making web pages interactive. Events are actions that occur in the browser, such as clicks, form submissions, or key presses. Event listeners are functions that wait for these events to occur and then respond accordingly.

Basics of Event Handling

  1. Events: Actions that happen in the browser (e.g., click, submit, mouseover).
  2. Event Listeners: Functions that execute when an event occurs.

How to Add Event Listeners

You can add event listeners using the addEventListener() method. This method takes two arguments:

  1. Event Type: The type of event to listen for (e.g., 'click', 'keydown').
  2. Event Handler: The function to run when the event occurs.

Example

Let's create a simple example to demonstrate event handling with JavaScript.

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Handling Example</title>
</head>
<body>
    <h1 id="welcome-message">Welcome!</h1>
    <button id="change-message-button">Change Message</button>
    <input type="text" id="name-input" placeholder="Enter your name">
    <button id="greet-button">Greet</button>
    <p id="greeting-message"></p>

    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js)

// Select elements
const welcomeMessage = document.getElementById('welcome-message');
const changeMessageButton = document.getElementById('change-message-button');
const nameInput = document.getElementById('name-input');
const greetButton = document.getElementById('greet-button');
const greetingMessage = document.getElementById('greeting-message');

// Event handler function for changing the welcome message
function changeWelcomeMessage() {
    welcomeMessage.textContent = 'Hello, World!';
}

// Event handler function for greeting
function greetUser() {
    const userName = nameInput.value;
    if (userName) {
        greetingMessage.textContent = `Hello, ${userName}!`;
    } else {
        greetingMessage.textContent = 'Please enter your name.';
    }
}

// Add event listeners
changeMessageButton.addEventListener('click', changeWelcomeMessage);
greetButton.addEventListener('click', greetUser);


Explanation

  1. Selecting Elements:

    • document.getElementById('welcome-message') selects the <h1> element with the ID welcome-message.
    • document.getElementById('change-message-button') selects the button that will change the welcome message.
    • document.getElementById('name-input') selects the input field where users type their names.
    • document.getElementById('greet-button') selects the button that will display a greeting.
    • document.getElementById('greeting-message') selects the paragraph where the greeting message will be shown.
  2. Event Handler Functions:

    • changeWelcomeMessage(): Changes the text content of the <h1> element when the button is clicked.
    • greetUser(): Retrieves the value from the input field and updates the paragraph with a personalized greeting. If the input is empty, it prompts the user to enter a name.
  3. Adding Event Listeners:

    • changeMessageButton.addEventListener('click', changeWelcomeMessage); attaches the changeWelcomeMessage function to the click event of the changeMessageButton.
    • greetButton.addEventListener('click', greetUser); attaches the greetUser function to the click event of the greetButton.









Post a Comment

0 Comments