Home > Software design >  btn1.addEventListener is not a function
btn1.addEventListener is not a function

Time:01-04

<div >
                    <h1 >STATUE OF UNITY</h1>
                    <P>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                         Necessitatibus sint nisi animi ipsum commodi illum fuga eos 
                         ad. Amet consectetur fugit adipisci praesentium rem eaque eos
                          laudantium, vitae sunt earum.
                    </P>
      </div>
<script>
        const clr=document.getElementsByClassName("colorchange");
        const btn1=document.getElementsByClassName("btn");

        btn1.addEventListener("click",myfunction)
        function myfunction(){
            clr.style.display="none";
        };
    </script>

I am not understand this error can you please tell what is the problem in my code??????????????.

CodePudding user response:

getElementsByClassName vs getElementsById your code will return a list of all the elements which contains colorchange in class.. therefore you need to get the first element

const clr = document.getElementsByClassName("colorchange");
const btn1 = document.getElementsByClassName("btn");

function myfunction() {
  clr[0].style.display = "none";
};

btn1[0].addEventListener("click", myfunction)
<div >
  <h1 >STATUE OF UNITY</h1>
  <P>Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus sint nisi animi ipsum commodi illum fuga eos ad. Amet consectetur fugit adipisci praesentium rem eaque eos laudantium, vitae sunt earum.
  </P>
  <input type="button"  value="hide">
</div>

CodePudding user response:

getElementsByClassName returns the HTMLCollection. It's array-like object.

You need to have a button with class "btn" in your code, and write smth like this:

const btn1 = document.getElementsByClassName("btn")[0]; 

or by using querySelector:

const btn1 = document.querySelector(".btn");

and then call:

btn1.addEventListener(...your code...) 

Best regards!

  • Related