Skip to main content

DOM Manipulation and CSS with JavaScript

In this tutorial, we will explore how to manipulate the DOM and apply CSS styles using JavaScript. This allows you to create dynamic and interactive web applications by modifying page elements and their styles.

Accessing DOM elements

Use JavaScript to access and manipulate DOM elements by using methods such as getElementById, getElementsByClassName, getElementsByTagName, and querySelector.

// Access an element by its ID
const elementById = document.getElementById('example');

// Access elements by their class name
const elementsByClassName = document.getElementsByClassName('example-class');

// Access elements by their tag name
const elementsByTagName = document.getElementsByTagName('p');

// Access the first element that matches a CSS selector
const elementByQuerySelector = document.querySelector('.example-class');

Modifying element styles

Change the style of a DOM element by accessing its style property and setting new values for specific CSS properties.

// Set the color and font size of an element = 'red'; = '24px';

Adding and removing CSS classes

Add or remove CSS classes from a DOM element using the classList property and methods such as add, remove, and toggle.

// Add a CSS class

// Remove a CSS class

// Toggle a CSS class

Manipulating element attributes

Modify element attributes, such as class, id, or data-* attributes, using JavaScript methods like getAttribute, setAttribute, and removeAttribute.

// Get the value of an attribute
const classAttributeValue = elementById.getAttribute('class');

// Set the value of an attribute
elementById.setAttribute('data-example', 'new value');

// Remove an attribute

Adding and removing elements

Create, modify, or delete elements in the DOM using methods such as createElement, appendChild, insertBefore, and removeChild.

// Create a new element
const newElement = document.createElement('div');

// Add the new element to the DOM

// Insert the new element before another element
elementById.insertBefore(newElement, elementByQuerySelector);

// Remove an element from the DOM


By combining JavaScript and CSS, you can create dynamic web applications that respond to user interactions, update content, and modify styles on the fly.