Skip to main content

Command Palette

Search for a command to run...

Day 8: DOM Manipulation in JavaScript

Published
4 min read
Day 8: DOM Manipulation in JavaScript

Welcome back to our JavaScript series! This week, we'll explore the Document Object Model (DOM) and learn how to manipulate it by using JavaScript. The DOM represents the structure of a web page, allowing us to dynamically change the content, structure, and style of the page.

What is the DOM?

The DOM is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM is a tree-like structure where each node represents a part of the document.

Selecting Elements

To manipulate the DOM, we first need to select the elements we want to work with. There are several methods for selecting elements in JavaScript:

getElementById

Selects an element by its ID.

let element = document.getElementById('myElement');

getElementsByClassName

Selects all elements with a specific class name. Returns a collection of elements.

let elements = document.getElementsByClassName('myClass');

getElementsByTagName

Selects all elements with a specific tag name. Returns a collection of elements.

let elements = document.getElementsByTagName('p');

querySelector

Selects the first element that matches a CSS selector.

let element = document.querySelector('.myClass');

querySelectorAll

Selects all elements that match a CSS selector. Returns a NodeList.

let elements = document.querySelectorAll('.myClass');

Changing Content

Once we have selected an element, we can change its content using the innerHTML or textContent properties.

innerHTML

Changes the HTML content of an element.

let element = document.getElementById('myElement');
element.innerHTML = '<p>New content</p>';

textContent

Changes the text content of an element.

let element = document.getElementById('myElement');
element.textContent = 'New text content';

Changing Styles

We can also change the styles of an element using the style property.

let element = document.getElementById('myElement');
element.style.color = 'red';
element.style.backgroundColor = 'yellow';
element.style.fontSize = '20px';

Adding and Removing Classes

We can add or remove CSS classes using the classList property.

Adding a Class

let element = document.getElementById('myElement');
element.classList.add('newClass');

Removing a Class

let element = document.getElementById('myElement');
element.classList.remove('newClass');

Toggling a Class

let element = document.getElementById('myElement');
element.classList.toggle('activeClass');

Creating and Removing Elements

We can create new elements and add them to the DOM, as well as remove existing elements.

Creating an Element

let newElement = document.createElement('div');
newElement.textContent = 'Hello, World!';
document.body.appendChild(newElement);

Removing an Element

let element = document.getElementById('myElement');
element.remove();

Event Listeners

Event listeners allow us to run JavaScript code in response to user actions, like clicks , mouse-over or key presses.

Adding an Event Listener

To add an event listener to an element, use the addEventListener method. This method takes two arguments: the event type (like 'click') and the function to run when the event occurs.

let button = document.getElementById('myButton');
button.addEventListener('click', function() {
    alert('Button clicked!');
});

Some Common Event Types

  • 'click': Fired when an element is clicked.

  • 'mouseover': Fired when the mouse pointer moves over an element.

  • 'mouseout': Fired when the mouse pointer moves out of an element.

  • 'keydown': Fired when a key is pressed down.

  • 'keyup': Fired when a key is released.

  • 'submit': Fired when a form is submitted.

Removing an Event Listener

To remove an event listener, use the removeEventListener method with the same arguments as addEventListener.

function handleClick() {
    alert('Button clicked!');
}

let button = document.getElementById('myButton');
button.addEventListener('click', handleClick);

// To remove the event listener
button.removeEventListener('click', handleClick);

Event Object

When an event occurs, an event object is automatically passed to the event handler function. This object contains useful information about the event.

let button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
    console.log('Event type:', event.type); // Output: Event type: click
    console.log('Target element:', event.target); // Output: Target element: <button id="myButton">...</button>
});

Summary

Today, we learned about the DOM and how to manipulate it using JavaScript. We covered selecting elements, changing content and styles, adding and removing classes, creating and removing elements, and handling events with event listeners. Understanding DOM manipulation is crucial for creating interactive web pages. Tomorrow, we'll continue exploring Handling & validation in Forms.

More from this blog

Mohit's blog

51 posts