March 15, 20206 yr I have a class that I am trying to adapt, but keep getting an undefined error. I am currently blind to the solution so am reaching out... <!DOCTYPE html> <html> <head> <style> .button { width: 40px; height: 40px; line-height: 40px; border: 1px solid #000; border-radius: 25px; font-family: "Comic Sans MS", cursive, sans-serif; text-align: center; margin: 0 1px 0 1px; float: left; } .button:hover { cursor: pointer; background-color: coral; } </style> </head> <body> <div id="buttons"> <div class="button">1</div> <div class="button">2</div> <div class="button">3</div> <div class="button">4</div> <div class="button">5</div> <div class="button">6</div> <div class="button">7</div> <div class="button">8</div> <div class="button">9</div> <div style="clear: both;"></div> </div> <script> function setup() { var buttons = document.getElementsByClassName("button"); sNo = parseInt(Math.random() * 2 + 89); if (sNo % 10 == 0) { buttons.style.backgroundColor = "cornflowerblue"; } else { buttons.style.backgroundColor = "gray"; } } setup(); </script> </body> </html>
March 15, 20206 yr Any reason why you're using DIV elements to create buttons with? Why not use a html BUTTON, they're accessible and intended to use as buttons.
March 16, 20206 yr Author 10 hours ago, BlueDreamer said: Any reason why you're using DIV elements to create buttons with? Why not use a html BUTTON, they're accessible and intended to use as buttons. Only that I have found in the past using DIVs offers much greater flexibility and control that using the buttons HTML code.
March 16, 20206 yr Author 1 hour ago, NOCK said: You can't use .style on a HTMLCollection which is what 'buttons' is. Run console.log(buttons) and you'll see. You need to loop through the collection and apply the style to each button individually. The following JS will work: <script> function setup() { var buttons = document.getElementsByClassName("button"); for (button of buttons) { var sNo = parseInt(Math.random() * 2 + 89); if (sNo % 10 == 0) { button.style.backgroundColor = "cornflowerblue"; } else { button.style.backgroundColor = "gray"; } } } setup(); </script> Thanks for this, makes complete sense and something I should have spotted. Feel like I am having a 'stupid' set of moments currently.
Create an account or sign in to comment