Want to display a message on the console with a button click

Asked 1 years ago, Updated 1 years ago, 328 views

I want to create a program that alternates on and off on the console every time I click a button, but it doesn't work when I press the button.When you load the page, "Uncaught TypeError: btn.addEventListener is not a function at a.js:11" appears on the console.

So I tried using onclick by rewriting the 11th line of the js file as "btn.onclick=change;", but in this case, the error message disappeared on the console, but when I pressed the button, nothing worked.

Could you tell me why addEventListner and onclick do not work?

let btn= document.getElementsByClassName("off");

const change=function(){
    if(btn.className=="off"){
        console.log("off");
    } else if(btn.className=="on"){
        console.log("on");
    }
};
btn.addEventListener("click", change); 
<!DOCTYPE html>
<html lang="ja">
    <head>
        <metacharset="utf-8"/>
        <title> Events: Task 1</title>
        <script type="text/javascript" src="a.js"></script>
    </head>

    <body>
        <section class="preview"></section>

        <button class="off">button</button>
    </body>
    <script></script>
</html>

javascript html

2022-09-30 21:57

2 Answers

Because in your code, btn is not the button element of HTML, but HTMLCollection with only one element.Note that the method name is getElementsByClassName and is plural Elements.

getElementsByClassName

If you want to remove the button element, remove one from the getElementsByClassName results.

let btn= document.getElementsByClassName("off")[0];//<-

const change=function(){
    if(btn.className=="off"){
        console.log("off");
    } else if(btn.className=="on"){
        console.log("on");
    }
};
btn.addEventListener("click", change); 
<!DOCTYPE html>
<html lang="ja">
    <head>
        <metacharset="utf-8"/>
        <title> Events: Task 1</title>
        <script type="text/javascript" src="a.js"></script>
    </head>

    <body>
        <section class="preview"></section>

        <button class="off">button</button>
    </body>
    <script></script>
</html>

"Also, it seems that the ""on and off alternately"" part was not fully implemented yet, so I left it as it is, and once the addEventListener works, you should be able to solve it yourself."


2022-09-30 21:57

Example code with multiple class names of "off" elements.

let btns= document.getElementsByClassName("off");
btns = Array.from(btns)

const change=function(btn){
    if(btn.className=="off"){
        console.log("off");
    } else if(btn.className=="on"){
        console.log("on");
    }
};

btns.forEach(function(btn){
    btn.addEventListener("click", change(btn)));
});


2022-09-30 21:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.