"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Change the Opacity of Multiple DIV Elements with querySelectorAll?

How to Change the Opacity of Multiple DIV Elements with querySelectorAll?

Posted on 2025-03-22
Browse:165

How to Change the Opacity of Multiple DIV Elements with querySelectorAll?

Using querySelectorAll to Modify Multiple Elements' Appearance

In the world of web development, it's often necessary to manipulate the style of multiple elements simultaneously. In this scenario, a JavaScript function exists to adjust the opacity of a specific DIV element. However, the challenge lies in applying this function to several DIVs at once.

Using getElementsByClassName initially seems like a viable approach, but it falls short in our case. Instead, querySelectorAll emerges as a more appropriate solution. Here's how the function can be implemented:

function changeOpacity(className) {
    var elems = document.querySelectorAll(className);
    var index = 0, length = elems.length;
    for ( ; index 

In this code, querySelectorAll retrieves a collection of all DIVs containing a specific class name. A for loop iterates over this collection, applying the desired style changes to each element.

As an alternative suggestion, consider using CSS classes to define styling values for multiple elements. This approach becomes useful when styling values are not dynamic. The code above can be modified to:

elems[index].classList.add('someclass');

By adding a CSS class that defines the desired opacity and transition values, the function can be simplified.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3