简体   繁体   中英

How to change height using DOM .style property by passing an array value in it?

I have to change the height of bars and make it equal to the random value that my loop generates. This value has to edit the bar-style class of my CSS under the div tag. I can change width, color, etc., when I use style property, however I cannot pass my random int value as height for some reason. I tried using template literals but that does not seem to work.

 let bars = []; let arr_length = 10; const sortArea = document.querySelector(".sort-area"); for (let i = 0; i < arr_length; i++) { // height of bars bars.push(Math.floor(Math.random() * 101)); const div = document.createElement("div"); sortArea.append(div); div.classList.add("bar-style"); const barStyle = document.querySelectorAll(".bar-style"); barStyle[i].style.height = `${bars[i]}`; //<-- main issue }
 .bar-style { border: 1px solid pink; margin: 2px; padding: 1.25px; background-color: #f1ff5c; width: 5px; }
 <body> <header class="header"> <h1>Sorting Visualiser</h1> <nav> <button class="btn new-array">New Array</button> <button type="button" class="btn bubble">Bubble Sort</button> <button type="button" class="btn selection">Selection Sort</button> <button type="button" class="btn insertion">Insertion Sort</button> </nav> </header> <main> <div class="sort-area"></div> </main> <script type="text/javascript" src="js_files/arr.js"></script> </body> </html>

strong text

You are not adding the unit of measurement.


You could do like this:
 barStyle[i].style.height = `${bars[i]}px`;

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