简体   繁体   中英

JavaScript for changing a <div> colour from a button press

I'm a little unsure why my code doesn't seem to be working when my html and JS code are within the same file. When the html and JS are separate, seems to be working fine. Can someone point out the error in my ways....I'm a newbie!!

HTML:

<div class="main">
    <div class="light"></div>
    <button onclick="chngCol()" id="burn">Burn!</button>
</div>

JavaScript:

chngCol() {
    if(document.getElementByClass('light').style.background == "#00ffff")
      { 
       document.getElementByClass('light').style.background = "#ffff00"; 
      } 
       else if(document.getElementByClass('light').style.background == "ffff00")
      {
       document.getElementByClass('light').style.background = "#ff00ff"; 
      }
       else if(document.getElementByClass('light').style.background == "#ff00ff")
      { 
       document.getElementByClass('light').style.background = "#00ffff";       
      }
   }

CSS:

    .light{
        width: 50px;
        height: 50px;
        background-color:#00ffff;
    }

All code is in the same document with the appropriate tags and however the error i'm getting in Chrome Console on the first { after calling chngCol.

There are a multitude of issues.

  • chngCol() { is not valid JS. Either function chngCol() { OR const chngCol = () =>
  • You need document.getElementsByClassName("light")[0] OR better, document.querySelector(".light")
  • You cannot read the background color of the element if it is not set in script first.

I think you meant to do this:

 let cnt = 0; const colors = ["#00ffff", "#ffff00", "#ff00ff"]; const chngCol = () => { cnt++; if (cnt >= colors.length) cnt = 0; // wrap document.querySelector('.light').style.background = colors[cnt]; // use the array } document.getElementById("burn").addEventListener("click", chngCol);
 .light { width: 50px; height: 50px; background-color: #00ffff; } #burn { width: 150px; font-weight: 700; }
 <div class="main"> <div class="light"></div> <button id="burn">Burn!</button> </div>

The document.getElementByClass selector is an array selector. In order to select your element you should select the first element of the array. Try this instead:

document.getElementsByClassName('light')[0].style.background

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