Reputation: 11920
I have a bit of JQuery in my app that adds a click event to a class. The click event just removes a class on the parent element.
$(function(){
$(".flash .close").on("click", function(){
$(this).parent().removeClass("active");
})
});
This is the only use of JQuery in my entire application, so I'd love to re-write this snippet without JQuery so I can eliminate that as a dependency all together.
However, I'm not sure where to begin in terms of implementing this click even in native javascript. I don't know much about JavaScript and the little that I do know involves frameworks like JQuery and React.
Thanks!
Upvotes: 0
Views: 1424
Reputation: 4536
Try this fiddle https://jsfiddle.net/z6uopyhy/1/
var flashCloseButton = document.getElementsByClassName('close');
for(var i = 0; i < flashCloseButton.length; i++){
flashCloseButton[i].addEventListener("click", function(e) {
this.parentElement.classList.remove("active");
});
}
Upvotes: 0
Reputation: 651
You can take reference from the source below for your learning perspective https://www.w3schools.com/js/js_htmldom_eventlistener.asp
Upvotes: 1
Reputation: 22510
Try with querySelectorAll
for select the element.Then classList.remove()
use for remove the class name of the parentElement
.
window.onload=function(){
document.querySelectorAll(".flash , .close").forEach(function(a){
a.addEventListener("click", function(){
this.parentElement.classList.remove("active");
})
})
}
.active{
color:red;
}
<div class="active">
<a class="flash">hi</a>
</div>
Upvotes: 2