logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Mastering DOM Manipulation and Event Handling in Vanilla JavaScript

author
Generated by
Abhishek Goyan

15/10/2024

vanilla-js

Sign in to read full article

Introduction to DOM Manipulation

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree-like hierarchy, allowing developers to access and manipulate the content, structure, and style of web pages dynamically.

Let's start with some basic DOM manipulation techniques:

Selecting Elements

To interact with DOM elements, we first need to select them. Here are some common methods:

// Select by ID const element = document.getElementById('myElement'); // Select by class name const elements = document.getElementsByClassName('myClass'); // Select by tag name const paragraphs = document.getElementsByTagName('p'); // Select using CSS selectors const firstButton = document.querySelector('button'); const allButtons = document.querySelectorAll('button');

Modifying Element Content

Once we've selected an element, we can modify its content:

// Change text content element.textContent = 'New text content'; // Change HTML content element.innerHTML = '<strong>New HTML content</strong>';

Modifying Element Attributes

We can also change element attributes:

// Set an attribute element.setAttribute('class', 'newClass'); // Get an attribute value const href = element.getAttribute('href'); // Remove an attribute element.removeAttribute('disabled');

Modifying Element Styles

Changing element styles is straightforward:

// Change a single style property element.style.color = 'red'; // Change multiple style properties Object.assign(element.style, { fontSize: '16px', fontWeight: 'bold', backgroundColor: '#f0f0f0' });

Creating and Removing Elements

Creating Elements

To create new elements dynamically:

// Create a new element const newParagraph = document.createElement('p'); newParagraph.textContent = 'This is a new paragraph.'; // Append the new element to an existing element document.body.appendChild(newParagraph);

Removing Elements

To remove elements from the DOM:

// Remove an element element.remove(); // Remove a child element parentElement.removeChild(childElement);

Event Handling

Event handling is crucial for creating interactive web applications. Let's explore some key concepts:

Adding Event Listeners

To respond to user actions, we add event listeners to elements:

const button = document.querySelector('button'); button.addEventListener('click', function() { console.log('Button clicked!'); });

Removing Event Listeners

It's important to remove event listeners when they're no longer needed:

function handleClick() { console.log('Button clicked!'); } button.addEventListener('click', handleClick); // Later, when you want to remove the listener button.removeEventListener('click', handleClick);

Event Object

The event object contains useful information about the event:

button.addEventListener('click', function(event) { console.log('Event type:', event.type); console.log('Target element:', event.target); console.log('Mouse coordinates:', event.clientX, event.clientY); });

Event Delegation

Event delegation is a powerful technique for handling events on multiple elements efficiently:

document.getElementById('parent-list').addEventListener('click', function(event) { if (event.target.tagName === 'LI') { console.log('Clicked on list item:', event.target.textContent); } });

Practical Example: Dynamic Todo List

Let's put it all together with a simple todo list application:

const todoForm = document.getElementById('todo-form'); const todoInput = document.getElementById('todo-input'); const todoList = document.getElementById('todo-list'); todoForm.addEventListener('submit', function(event) { event.preventDefault(); if (todoInput.value.trim() === '') return; const todoItem = document.createElement('li'); todoItem.textContent = todoInput.value; const deleteButton = document.createElement('button'); deleteButton.textContent = 'Delete'; deleteButton.addEventListener('click', function() { todoList.removeChild(todoItem); }); todoItem.appendChild(deleteButton); todoList.appendChild(todoItem); todoInput.value = ''; });

This example demonstrates how to create elements, handle form submissions, and dynamically update the DOM.

By mastering these DOM manipulation and event handling techniques, you'll be well-equipped to create dynamic and interactive web applications using vanilla JavaScript. Remember to practice these concepts regularly and explore more advanced topics to further enhance your skills.

Popular Tags

vanilla-jsdom-manipulationevent-handling

Share now!

Like & Bookmark!

Related Collections

  • JavaScript Mastery: From Basics to Advanced Techniques

    15/10/2024 | VanillaJS

  • JavaScript Interview Mastery: 20 Essential Concepts

    22/10/2024 | VanillaJS

  • JavaScript Coding Challenges for Interviews

    14/09/2024 | VanillaJS

Related Articles

  • Understanding the JavaScript Event Loop

    22/10/2024 | VanillaJS

  • Understanding Functions and Scope in Vanilla JavaScript

    15/10/2024 | VanillaJS

  • Understanding JavaScript Garbage Collection

    22/10/2024 | VanillaJS

  • Diving into Vanilla JavaScript

    15/10/2024 | VanillaJS

  • Mastering JavaScript Fundamentals

    15/10/2024 | VanillaJS

  • Understanding Rest and Spread Operators in Vanilla JavaScript

    22/10/2024 | VanillaJS

  • Mastering Modules and Modular Design Patterns in Vanilla JavaScript

    15/10/2024 | VanillaJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design