简体   繁体   中英

Why doesn't the button change color? (how to change html element's class)

I'm trying to make an website with bootstrap and stuff, and I want to change a class for elements. I saw my code is not working, so I made an example to see where I'm wrong. I know I can solve it easily with django, but I want to know why my code doesn't work.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
    .blue{
        background-color: blue
    }
    .green{
        background-color: green
    }
    </style>
</head>
<body>
    <button type ="button" id="btn1" class = "blue" onclick="clicked()">hello</button>
    <script>
        function clicked(){
            document.getElementByid("btn1").className = "green"
        }
    </script>
</body>
</html>

after clicking the button, the button remains blue. thank you for helping.

There was a syntax error ( or typo ) in your code. You were using document.getElementByid with a small i while the valid function has a capital I ie document.getElementById .

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .blue{ background-color: blue } .green{ background-color: green } </style> </head> <body> <button type ="button" id="btn1" class = "blue" onclick="clicked()">hello</button> <script> function clicked(){ document.getElementById("btn1").className = "green" } </script> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM