Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...