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.

JavaScript
// 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.

JavaScript
// Set the color and font size of an element
elementById.style.color = 'red';
elementById.style.fontSize = '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.

JavaScript
// Add a CSS class
elementById.classList.add('new-class');

// Remove a CSS class
elementById.classList.remove('old-class');

// Toggle a CSS class
elementById.classList.toggle('toggle-class');

Manipulating element attributes

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

JavaScript
// 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
elementById.removeAttribute('data-example');

Adding and removing elements

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

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

// Add the new element to the DOM
elementById.appendChild(newElement);

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

// Remove an element from the DOM
elementById.removeChild(newElement);

Conclusion

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