bar azaria bar azaria - 4 months ago 7
CSS Question

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.

Answer

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 i.e. 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>

Comments