I am new to using Javascript to Web development.
Recently, I've encountered this problem when trying to use DOMContentLoaded to my code below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>hello</title>
<script>
document.addEventListner('DOMContentLoaded', function(event) => {
document.querySelector('#red').addEventListener('click', function() {
let button = document.querySelector('button');
button.style.backgroundColor = 'red';
event.preventDefault();
});
});
</script>
</head>
<body>
<button id='red'> Red </button>
</body>
</html>
When I clicked the button, the color of the button did not change
I think that I've correctly implemented my code and added DOMContentLoaded event when placing the <script> in the head of my html code. However, this code does not work and so far I still not yet figure out where does the problem lies.
Could anyone help me with this matter and give me an explaination please? Thank you so much!
place
<script>in the body after the tags It's will work Good luck