简体   繁体   中英

how to change multiple divs with the same class through querySelector

I was wondering how it is possible to change the class on multiple divs at once via js. In the example below only the first use of the class gets recognized, all afterwards are ignore. querySelectorAll doesn't seem to work. Thanks in advance

 function setZoom(color) { document.querySelector('.var').style.color = color; }
 .var { margin-top:20px; color:black; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label for="input1" value="green" onclick="setZoom('blue')"> <button>green</button> </label> <label for="input2" value="red" onclick="setZoom('yellow')"> <button>btn-yellow,</button> </label> <label for="input3" value="pink" onclick="setZoom('pink')"> <button>btn-pink</button> </label> <div class="var"> content div 1 </div> <div class="var"> content div 2 </div> <div class="var"> content div 3 </div>

You will need querySelectorAll which will return a nodelist. Then you can iterate over that using forEach and change the style

 function setZoom(color) { document.querySelectorAll('.var').forEach((item) => { item.style.color = color; }) }
 .var { margin-top: 20px; color: black; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label for="input1" value="green" onclick="setZoom('blue')"> <button>green</button> </label> <label for="input2" value="red" onclick="setZoom('yellow')"> <button>btn-yellow,</button> </label> <label for="input3" value="pink" onclick="setZoom('pink')"> <button>btn-pink</button> </label> <div class="var"> content div 1 </div> <div class="var"> content div 2 </div> <div class="var"> content div 3 </div>

I think change this,

function setZoom(color) {
document.querySelector('.var').style.color = color; 
}

to this,

function setZoom(color) {
document.querySelectorAll('.var').style.color = color; 
}

The querySelector select only one targeted element and the querySelectorAll select all the targeted elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM