Reputation: 893
I have the following function which when triggered will make a DIV become semi-transparent.
function changeOpacity(el) {
var elem = document.getElementById(el);
elem.style.transition = "opacity 0.5s linear 0s";
elem.style.opacity = 0.5;
}
However I would like this function to apply to several DIVs simultaneously. I tried giving each DIV the same class name and then using getElementsByClassName
but couldn't figure out how to implement it.
Would querySelectorAll
be more appropriate and if so how would I implement it?
Upvotes: 52
Views: 155537
Reputation: 270
Another way to do this using Object entries within a FOR-IN:
let elements = document.querySelectorAll('[attribute name]');
if (elements != undefined) {
for (let element in Object.entries(elements)) {
elements[element].style.transition = 'opacity 0.5s linear 0s';
elements[element].style.opacity = 0.5;
}
}
Modify for your needs.
Upvotes: 1
Reputation: 95
Use the new ES6 Array.map() to loop over every item and change the properties
document.querySelectorAll(selector).map(item => {
item.style.transition = "opacity 0.5s linear 0s";
item.style.opacity = 0.5;
})
Upvotes: 0
Reputation: 9691
I would select them with a querySelectorAll and loop over them.
function changeOpacity(className) {
var elems = document.querySelectorAll(className);
var index = 0, length = elems.length;
for ( ; index < length; index++) {
elems[index].style.transition = "opacity 0.5s linear 0s";
elems[index].style.opacity = 0.5;
}
}
Edit: As a comment said you might be better off putting styling values in a CSS class if they are not dynamic and use:
elems[index].classList.add('someclass');
Upvotes: 55
Reputation: 2867
Another way this can be done is with forEach()
and ES6+
function changeOpacity(className) {
document.querySelectorAll(className).forEach(el => {
el.style.transition = "opacity 0.5s linear 0s";
el.style.opacity = 0.5;
});
}
I especially like this syntax when only one style property needs to be updated. For example, if you only needed to change the opacity, and not the transition, you could use a single line:
function setOpacity(className) {
document.querySelectorAll(className).forEach(el => el.style.opacity = 0.5);
}
You could then use a separate method for setting the transition:
function setTransition(className) {
document.querySelectorAll(className).forEach(
el => el.style.transition = "opacity 0.5s linear 0s";
});
}
Upvotes: 35