Blog>
Snippets

Manipulating Classes and Styles

Provide code examples for adding, removing, or toggling CSS classes on an element, and updating style properties using Renderer2.
// Adding a CSS class to an element
const element = document.querySelector('.my-element');
element.classList.add('new-class');
This code selects an element with the class 'my-element' and adds the 'new-class' CSS class to it.
// Removing a CSS class from an element
const element = document.querySelector('.my-element');
element.classList.remove('existing-class');
This code selects an element with the class 'my-element' and removes the 'existing-class' CSS class from it.
// Toggling a CSS class on an element
const element = document.querySelector('.my-element');
element.classList.toggle('toggle-class');
This code selects an element with the class 'my-element' and toggles the 'toggle-class' CSS class on it. If the class exists, it is removed; if it does not exist, it is added.
// Updating an element's style property directly
const element = document.querySelector('.my-element');
element.style.color = 'blue';
This code selects an element with the class 'my-element' and changes its text color to blue by setting the style property directly.
// Using Renderer2 to add a class
import { Renderer2 } from '@angular/core';

// Assume renderer is an instance of Renderer2
// and element is a reference to an element
renderer.addClass(element, 'new-class');
This Angular-specific code uses Renderer2 to add the 'new-class' CSS class to an element.
// Using Renderer2 to remove a class
import { Renderer2 } from '@angular/core';

// Assume renderer is an instance of Renderer2
// and element is a reference to an element
renderer.removeClass(element, 'existing-class');
This Angular-specific code uses Renderer2 to remove the 'existing-class' CSS class from an element.
// Using Renderer2 to set a style property
import { Renderer2 } from '@angular/core';

// Assume renderer is an instance of Renderer2
// and element is a reference to an element
renderer.setStyle(element, 'color', 'blue');
This Angular-specific code uses Renderer2 to set the 'color' style property to 'blue' on an element.