user2490003
user2490003

Reputation: 11920

Implementing an onclick event without JQuery

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

Answers (3)

Andrei Todorut
Andrei Todorut

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

Dinesh K
Dinesh K

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

prasanth
prasanth

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

Related Questions