I have an alert in my html code:
<div class="alert alert-success alert-dismissible fade show d-flex align-items-center justify-content-center" id="alert" style="display:none;">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
<span id="msg">Success</span>
</div>
Initially, the alert should be hidden. Upon clicking the submit button in my script, it should show the danger alert. This is my js:
document.getElementById("submit").addEventListener("click",function(){
document.getElementById("alert").className="alert alert-danger alert-dismissible fade show d-flex align-items-center justify-content-center";
document.getElementById("msg").innerHTML="Danger";
document.getElementById("alert").style.display="block";
})
But when I execute the code, the alert isn't hidden at all. Secondly, upon clicking the submit button, I get the following error:
Uncaught TypeError: Cannot set properties of null (setting 'className')
Why is that? Please help me.
Does the style flag !important helps for hiding?
style="display:none !important;"
this is how i got it to work fine:
<div class="alert alert-success alert-dismissible fade show d-flex align-items-center justify-content-center" id="alert" style="display:none !important;">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
<span id="msg">Success</span>
</div>
<input type="submit" id="submit" value="click me">
<script>
document.getElementById("submit").addEventListener("click", function () {
document.getElementById("alert").className = "alert alert-danger alert-dismissible fade show d-flex align-items-center justify-content-center";
document.getElementById("msg").innerHTML = "Danger";
document.getElementById("alert").style.display = "block";
});
</script>