Your code has many of the same IDs. The ID attribute is meant to be a unique ID all throughout the entire HTML document. So your jQuery tries to remove just the first ID and that's why only the first ID works.
For starters, change all of your #alert
s and #close
s to classes in the HTML and the CSS (for mere styling purposes and a cleaner document). And then for your jQuery, in order to avoid having to come up with a new ID every single time, apply an onclick
listener to each member of the class, and then proceed to remove the parent of the clicked element, that way it will only remove the alert that contains the x
.
Here is an example of what I mean:
HTML:
<div id="alert-container">
<div class="alert info showAlert">
<div class="content">
<i class="fas fa-exclamation-circle"></i>
<p>Warning: This is a warning alert!</p>
</div>
<button class="close">x</button>
</div>
<div class="alert info showAlert">
<div class="content">
<i class="fas fa-exclamation-circle"></i>
<p>Warning: This is a warning alert!</p>
</div>
<button class="close">x</button>
</div>
<div class="alert info showAlert">
<div class="content">
<i class="fas fa-exclamation-circle"></i>
<p>Warning: This is a warning alert!</p>
</div>
<button class="close">x</button>
</div>
</div>
CSS: (just an excerpt - apply this everywhere)
.alert{ /*Instead of #alert*/
display: flex;
max-width: 540px;
margin-left: 12px;
margin-bottom: 10px;
border-radius: 5px;
padding: 0 12px 0 12px;
}
Basically change all of your #alert
s #content
s and #close
s to .alert
, .content
, and .close
in your CSS
And for your jQuery, something like this is what I was talking about:
JavaScript:
$(".close").each((index, closeButton) => {
//In your HTML the immediate parent of the button is the alert so this is how we will access it for each button since they are all different
var alert = $(closeButton).parent();
$(closeButton).click(function() {
$(alert).removeClass("showAlert");
$(alert).addClass("hideAlert");
setTimeout(() => {
$(alert).remove()
}, 500);
});
});
That should work but I haven't tested it myself