How to Use JavaScript setAttribute to Change Classes for Multiple Elements: Convert publish_0 to publish_1 on Button Click

In modern web development, dynamically modifying element classes is a common task—whether you’re toggling styles, updating component states, or triggering functionality based on user interactions. One powerful way to manipulate classes is using JavaScript’s setAttribute method, which allows you to directly modify an element’s attributes, including the class attribute.

In this guide, we’ll walk through a practical example: changing the class of multiple elements from publish_0 to publish_1 when a button is clicked using setAttribute. We’ll cover everything from setup to troubleshooting, ensuring you understand both the "how" and "why" behind each step.

Table of Contents#

Understanding setAttribute and the class Attribute#

Before diving into the implementation, let’s clarify two key concepts:

What is setAttribute?#

The setAttribute method is a built-in JavaScript function that modifies the value of an attribute on a DOM element. Its syntax is:

element.setAttribute(attributeName, attributeValue);  

For example, element.setAttribute('class', 'new-class') sets the class attribute of element to new-class.

The class Attribute#

The class attribute in HTML defines one or more class names for an element, which are used to apply CSS styles or target elements with JavaScript. When you use setAttribute('class', 'publish_1'), you replace the entire value of the class attribute. This means any existing classes on the element will be overwritten (more on this later!).

Prerequisites#

To follow along, you’ll need:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • A code editor (e.g., VS Code) and a web browser (e.g., Chrome) to test your code.

Step-by-Step Implementation#

Let’s build a working example where clicking a button converts all elements with the class publish_0 to publish_1.

1. Set Up the HTML Structure#

First, create an HTML file with:

  • Multiple elements (e.g., <div> or <p>) that initially have the class publish_0.
  • A button to trigger the class change.
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>Change Classes with setAttribute</title>  
    <link rel="stylesheet" href="styles.css"> <!-- Link to CSS -->  
</head>  
<body>  
    <h1>Article Status</h1>  
 
    <!-- Elements with initial class "publish_0" -->  
    <div class="publish_0">Article 1</div>  
    <div class="publish_0">Article 2</div>  
    <div class="publish_0">Article 3</div>  
 
    <!-- Button to trigger class change -->  
    <button id="changeClassBtn">Publish All Articles</button>  
 
    <script src="script.js"></script> <!-- Link to JavaScript -->  
</body>  
</html>  

2. Style Classes with CSS#

Next, create a styles.css file to visually distinguish publish_0 (unpublished) and publish_1 (published) elements. This helps verify the class change works.

/* Style for unpublished articles (publish_0) */  
.publish_0 {  
    color: #ff4d4d; /* Red text */  
    margin: 10px 0;  
    padding: 10px;  
    border: 1px solid #ffcccc;  
}  
 
/* Style for published articles (publish_1) */  
.publish_1 {  
    color: #4CAF50; /* Green text */  
    margin: 10px 0;  
    padding: 10px;  
    border: 1px solid #ccffcc;  
}  
 
/* Style the button */  
#changeClassBtn {  
    margin-top: 20px;  
    padding: 10px 20px;  
    background-color: #007bff;  
    color: white;  
    border: none;  
    border-radius: 4px;  
    cursor: pointer;  
}  
 
#changeClassBtn:hover {  
    background-color: #0056b3;  
}  

3. Add JavaScript Logic#

Finally, create a script.js file to handle the button click and class modification. Here’s the step-by-step breakdown:

Step 3.1: Wait for the DOM to Load#

Ensure your JavaScript runs after the HTML elements are loaded. Wrap your code in DOMContentLoaded to avoid selecting elements that don’t exist yet.

document.addEventListener('DOMContentLoaded', function() {  
    // Code here will run after the DOM is fully loaded  
});  

Step 3.2: Select the Button and Add a Click Listener#

Target the button by its id (changeClassBtn) and attach a click event listener to trigger the class change.

document.addEventListener('DOMContentLoaded', function() {  
    const changeBtn = document.getElementById('changeClassBtn');  
 
    // Add click event listener to the button  
    changeBtn.addEventListener('click', function() {  
        // Logic to change classes goes here  
    });  
});  

Step 3.3: Select Elements with publish_0 Class#

Use document.getElementsByClassName('publish_0') or document.querySelectorAll('.publish_0') to select all elements with the publish_0 class.

document.addEventListener('DOMContentLoaded', function() {  
    const changeBtn = document.getElementById('changeClassBtn');  
 
    changeBtn.addEventListener('click', function() {  
        // Select all elements with class "publish_0"  
        const publish0Elements = document.getElementsByClassName('publish_0');  
        // Alternatively: const publish0Elements = document.querySelectorAll('.publish_0');  
    });  
});  

Step 3.4: Loop Through Elements and Update Classes#

Loop through the selected elements and use setAttribute('class', 'publish_1') to replace their class with publish_1.

⚠️ Note: getElementsByClassName returns a live HTMLCollection, which updates as the DOM changes. To avoid issues mid-loop, convert it to an array first.

document.addEventListener('DOMContentLoaded', function() {  
    const changeBtn = document.getElementById('changeClassBtn');  
 
    changeBtn.addEventListener('click', function() {  
        // Get all elements with class "publish_0" and convert to array  
        const publish0Elements = Array.from(document.getElementsByClassName('publish_0'));  
 
        // Loop through each element  
        publish0Elements.forEach(element => {  
            // Use setAttribute to replace the "class" attribute with "publish_1"  
            element.setAttribute('class', 'publish_1');  
        });  
    });  
});  

Full JavaScript Code#

Putting it all together:

document.addEventListener('DOMContentLoaded', function() {  
    const changeBtn = document.getElementById('changeClassBtn');  
 
    changeBtn.addEventListener('click', function() {  
        // Convert HTMLCollection to array for safe looping  
        const publish0Elements = Array.from(document.getElementsByClassName('publish_0'));  
 
        publish0Elements.forEach(element => {  
            // Replace the entire class attribute with "publish_1"  
            element.setAttribute('class', 'publish_1');  
            console.log('Class updated for:', element); // Optional: Verify in console  
        });  
    });  
});  

Troubleshooting Common Issues#

1. Elements Not Updating? Check DOM Load Order#

If your JavaScript runs before the HTML elements are parsed, getElementsByClassName will return an empty list. Always wrap code in DOMContentLoaded or place the <script> tag at the end of the <body>.

2. Existing Classes Are Lost#

setAttribute('class', 'publish_1') replaces all existing classes. For example, if an element has class="publish_0 featured", it will become class="publish_1" (losing featured).

Fix: If elements have multiple classes, use classList instead (see next section).

3. Live HTMLCollection Issues#

If you don’t convert HTMLCollection to an array, looping with for may skip elements (since the collection updates as classes change). Always convert to an array with Array.from() or spread syntax [...elements].

4. Typos in Class Names#

Double-check for typos (e.g., publish_O instead of publish_0). Use browser DevTools (Elements tab) to inspect classes.

When to Use setAttribute vs. classList#

While setAttribute works for simple class replacement, classList is often better for modifying classes without overwriting others. For example:

// Replace "publish_0" with "publish_1" without affecting other classes  
element.classList.replace('publish_0', 'publish_1');  

Use setAttribute only when you intentionally want to overwrite all classes. For most cases, classList (with add, remove, or replace) is safer and more readable.

Conclusion#

You now know how to use setAttribute to dynamically change classes for multiple elements on a button click. Here’s a quick recap:

  1. Set up HTML elements with the initial class (publish_0) and a trigger button.
  2. Style classes with CSS to visualize changes.
  3. Use JavaScript to listen for button clicks, select target elements, and update their classes with setAttribute.

Remember to handle edge cases like DOM load order and existing classes. For advanced use cases, consider classList for more granular control.

References#