0

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!

5
  • removing jquery tag Commented Jun 23, 2017 at 6:17
  • querySelectorAll, addEventListener, classList. Learn how to use it, seems like a pretty basic task. Commented Jun 23, 2017 at 6:19
  • add , in between elements class name. Commented Jun 23, 2017 at 6:20
  • Thanks @epascarello - would you mind detailing that a bit further? I'm not sure how any of those are implemented. Commented Jun 23, 2017 at 6:20
  • developer.mozilla.org/en-US/docs/Web/JavaScript Commented Jun 23, 2017 at 6:21

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you :)
1

You can take reference from the source below for your learning perspective https://www.w3schools.com/js/js_htmldom_eventlistener.asp

Comments

0

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");
     });
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.