Home > OS >  In Javascript how do you change the color and backgroundColor for each element in a list when you cl
In Javascript how do you change the color and backgroundColor for each element in a list when you cl

Time:11-06

I have a list of elements from numbers 1 to 5. I'm trying to make it so that when I click on any one of them, the circle changes to grey, and the number inside the circle changes to white. Right now my code only allows the background color to change to grey but not the number inside of it to change to white. How can I make it to that it changes to both colors when I click on anyone of them? Here it shows some of them are clicked.

This is the code for my Javascript.

const number_list = document.querySelectorAll(".num");

number_list.forEach((element) => {
  element.onclick = () => {
    element.style.color == "#ffffff";
    element.style.backgroundColor = "#7f8c9c";
  };
});

This is the code for my HTML.

<div >
  <ul>
    <li ><span>1</span></li>
    <li ><span>2</span></li>
    <li ><span>3</span></li>
    <li ><span>4</span></li>
    <li ><span>5</span></li>
  </ul>
</div>

CodePudding user response:

I have no idea if this is a standard nor a good approach, but it works for me on Firefox, Safari, Opera and Chrome.

And forgive me but I changed the list tags to "div" tags.

Here is the code:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
    <style>
        #mainContainer{
            width:auto;
            height:auto;
            font-size:1.6em;
        }
    </style>
</head>
<body>
    <div id="mainContainer">
        <div >
              <div id="num_1" ><span>&lt;div1 id="num_1" &gt;</span></div>
              <div id="num_2" ><span>&lt;div1 id="num_2" &gt;</span></div>
              <div id="num_3" ><span>&lt;div1 id="num_3" &gt;</span></div>
              <div id="num_4" ><span>&lt;div1 id="num_4" &gt;</span></div>
              <div id="num_5" ><span>&lt;div1 id="num_5" &gt;</span></div>
        </div>
    <script>
        let i;
        let j;
        let k;
        let arr = new Array();
        function swapColors(e){
            for(j = 0; j<arr.length; j  ){
                // 1 reset all the default colors
                arr[j].style.backgroundColor="#ffffff";
                arr[j].style.color = "#000000"
            }
            // Set the color for the clicked div
            e.target.parentNode.style.backgroundColor="#aaaaaa";
            e.target.parentNode.style.color = "#ffffff"
        }
        for(i = 1; i<=5; i  ){
            arr.push(document.getElementById("num_"   i));
        }
        for(k = 0; k<=arr.length; k  ){
            arr[k].addEventListener("click", swapColors);
        }
    </script>
    </div>
</body>
</html>

CodePudding user response:

element.style.color == "#ffffff";

The above Syntax is wrong, You have used == instead of =

change the above code to element.style.color = "#ffffff"; and it will work

  • Related