0

I have to make it so that when I hover over the cell the background color of the cell changes into a random color but I'm facing some issues Here is the code, for some reason it only works on the first cell. I tried the same making a 3x3 table with only multiple divs, but I'm facing the same issue

var bgc = document.getElementById("cell");
function change(){
const bg = Math.floor(Math.random()*16777215).toString(16);
bgc.style.backgroundColor = "#" + bg;
}
bgc.addEventListener("mouseenter", change);
bgc.addEventListener("mouseout", function() {
    bgc.style.backgroundColor = "white"
});
table {
    display:table;
    width:100%;
    height:100%;
    border:1px solid #000;
}
#row {
    display:table-row;
    height:100%;
}
#cell {
    padding: 20px;
    display:table-cell;
    width:33%;
    height:100%;
    border:1px solid black;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>change color</title>
    <link rel="stylesheet" href="./cs/style.css">
</head>
<body>
   
        <table class="table">
            <tr id="row">
                <td id="cell">1</td>
                <td id="cell">2</td>
                <td id="cell">3</td>
            </tr>
            <tr id="row">
                <td id="cell">4</td>
                <td id="cell">5</td>
                <td id="cell">6</td>
            </tr>
            <tr id="row">
                <td id="cell">7</td>
                <td id="cell">8</td>
                <td id="cell">9</td>
            </tr>
        </table>
    <script src="./js/main.js"></script>
</body>
</html>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Because ids are expected to be unique by web standards, and `getElementById` only returns the first match – Taplar Dec 03 '20 at 17:32
  • 1
    If your identifier for the elements needs to repeat, it should be a class instead, and use the `getElementsByClassName` or `querySelectorAll` methods for lookup – Taplar Dec 03 '20 at 17:33
  • @Taplar - Spot on. There **has** to be a good dupetarget for this. – T.J. Crowder Dec 03 '20 at 17:34
  • https://stackoverflow.com/questions/59887834/getting-the-value-of-the-input-field-using-jquery/59888053#59888053 https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return – Taplar Dec 03 '20 at 17:34

0 Answers0