Jump to content

Tried to convert simple jquery code to vanilla js


atheneor
 Share

Recommended Posts

Hi guys, 

I tried to convert the following jquery code to vanilla js. It seems like I've made mistake. 

$(".menu-link").click(function() {
  $("#menu").toggleClass("active");
  $(".container").toggleClass("active");
});
document.querySelectorAll(".menu-link").addEventListener("click", () => {
  var menu = document.querySelector("#menu");
  menu.classList.toggle("active");
  var container = document.querySelector(".container");
  container.classList.toggle("active");
});

Thanks a lot!

Link to comment
Share on other sites

9 hours ago, atheneor said:

It seems like I've made mistake. 

Just one, I think. document.querySelectorAll returns a NodeList. Unlike with jquery collections, you can't call addEventListener on the NodeList but rather need to iterate over its elements and attach a listener to each one.

Array.forEach.call(nodeList, function(el) { el.addEventListener(/* your class toggle code here */); })

 

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...