Apply Styles to Class with JavaScript

Apply Styles to Class with JavaScript

In this tutorial, we will create a JavaScript function that takes two parameters: a class name and a style object. The function will apply the styles from the style object to all elements on the page with the specified class name.

First, let’s create an HTML file with some sample elements that have the class name “foo”:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Apply Styles to Elements by Class Name</title>
</head>
<body>
  <div class="foo">Element 1</div>
  <div class="foo">Element 2</div>
  <div class="bar">Element 3</div>
  <script src="script.js"></script>
</body>
</html>

Now, create a JavaScript file named ‘script.js’ and write the function applyStylesToClass:

script.js

function applyStylesToClass(className, styles) {
  const elements = document.getElementsByClassName(className);

  for (const element of elements) {
    for (const [property, value] of Object.entries(styles)) {
      element.style[property] = value;
    }
  }
}

This function first selects all elements with the given class name using document.getElementsByClassName(). It then iterates through each element and applies the styles from the style object. It does this by looping through the object entries and assigning each style property and value to the element’s style property.

To test the function, call applyStylesToClass with the class name “foo” and a style object with the properties “color” and “backgroundColor”:

const className = 'foo';
const styles = {
  color: 'white',
  backgroundColor: 'purple',
};

applyStylesToClass(className, styles);

After running this code, all elements on the page with the class “foo” will have the text color set to white and the background color set to purple.

Apply Styles to Class with JavaScript

That’s it! You can now use this function to easily modify the styles of groups of elements in your projects.