JAVASCRIPT

Batch Updating Multiple Styles and Classes on DOM Elements

Discover how to quickly and efficiently update multiple CSS styles or manage several class names on a DOM element using a single JavaScript operation.

<style>
  .highlight { background-color: yellow; border: 1px solid orange; }
  .large-text { font-size: 20px; }
  .red-text { color: red; }
</style>

<p id="myParagraph" class="original-class">This is a paragraph to style and classify.</p>

<script>
  const myParagraph = document.getElementById('myParagraph');

  // 1. Batch apply multiple inline styles using cssText
  myParagraph.style.cssText = 'color: purple; font-family: Arial; margin-top: 20px;';
  console.log('Applied multiple inline styles via cssText.');

  // 2. Add multiple classes simultaneously
  myParagraph.classList.add('highlight', 'large-text');
  console.log('Added multiple classes.');

  // 3. Remove multiple classes simultaneously
  setTimeout(() => {
    myParagraph.classList.remove('original-class', 'highlight');
    console.log('Removed multiple classes.');
  }, 1500);

  // 4. Toggle a class (single or multiple if supported, but typically single)
  setTimeout(() => {
    myParagraph.classList.toggle('red-text');
    console.log('Toggled red-text class (on).');
  }, 3000);

  setTimeout(() => {
    myParagraph.classList.toggle('red-text');
    console.log('Toggled red-text class (off).');
  }, 4500);

  // 5. Check if an element has a class
  console.log('Has large-text class:', myParagraph.classList.contains('large-text'));
</script>
How it works: This snippet showcases efficient ways to manage element styles and classes. Setting `element.style.cssText` allows you to apply multiple inline CSS properties in one go, overwriting any previous inline styles. The `classList` API is used to manage CSS classes: `add()`, `remove()`, and `toggle()` can accept multiple class names as arguments for bulk operations, making it easy to apply or remove several classes at once. `contains()` checks for the presence of a class.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs