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?
First, select the element by using DOM methods such as document. querySelector() . The selected element has the style property that allows you to set the various styles to the element. Then, set the values of the properties of the style object.
The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.
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');
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"; }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With