Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

javascript - Using querySelectorAll to change the style property of multiple elements

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...