Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  57] [ 4]  / answers: 1 / hits: 113695  / 9 Years ago, fri, october 16, 2015, 12:00:00

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?


More From » html

 Answers
23

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');

[#64709] Wednesday, October 14, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janiajohnnad

Total Points: 146
Total Questions: 92
Total Answers: 107

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
janiajohnnad questions
Tue, Mar 30, 21, 00:00, 3 Years ago
Sun, Feb 7, 21, 00:00, 3 Years ago
Fri, Nov 6, 20, 00:00, 4 Years ago
Thu, Jun 18, 20, 00:00, 4 Years ago
;