-1

Even before I click the button the h1 tagged element comes yellow what should I do to fix it? Just want to make them yellow when I click on the button.

<html>
<head></head>
<body>  

<h1>Hello</h1>

<h2>World</h2>

<h1>test</h1>


<button id="button">click</button>
<script>
    var x = document.getElementById("button");

    x.addEventListener("onclick",change());

    function change(){
        var myNodes = document.getElementsByTagName("h1");

        for (var i = 0; i < myNodes.length ; i++) {
            myNodes[i].style.backgroundColor  = "yellow";
        }
    }

</script>

</body>
</html>
Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
alkanschtein
  • 305
  • 1
  • 13

2 Answers2

1

addEventListner accepts a function, rather than the return value to a function. Your change() is calling the function change, and the return value is being passed to addEventListener.

<script>
        const button = document.getElementById("button");
    
        button.addEventListener("click", change);
    
        function change(){
            const myNodes = document.getElementsByTagName("h1");
            for (let i = 0; i < myNodes.length ; i++) {
                myNodes[i].style.backgroundColor  = "yellow";
            }
        }
    </script>

There are easier and more graceful ways of accomplishing this, but that is beyond the scope of this answer.

Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
zabusa
  • 2,520
  • 21
  • 25
0

Two issues in your js snippet first in x.addEventListener("onclick",change());

the event should be click instead of onclick,secondly change() will immediately call the function , but x.addEventListener("click",change) will trigger the function only when it is clicked

var x = document.getElementById("button");

x.addEventListener("click", change);

function change() {
  var myNodes = document.getElementsByTagName("h1");

  for (var i = 0; i < myNodes.length; i++) {
    myNodes[i].style.backgroundColor = "yellow";
  }
}
<h1>Hello </h1>

<h2>World</h2>

<h1>test</h1>


<button id="button">click</button>
brk
  • 48,835
  • 10
  • 56
  • 78