You need to use defer or move the script tag to the end of the body.
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById("mainButton");
btn.onclick = function(){
alert("You shouldn't have clicked this button!");
};
});
</script>
</head>
<body>
<button id="mainButton">Do not click this button</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="mainButton">Do not click this button</button>
<script>
const btn = document.getElementById("mainButton");
btn.onclick = function(){
alert("You shouldn't have clicked this button!");
};
</script>
</body>
</html>