Majonez.exe
Majonez.exe

Reputation: 432

Convert Jquery to VanillaJS

I don't know how to rewrite this code from Jquery to VanillaJS. I've been tired for a few days and I haven't found a solution.

I think I've already searched the whole Internet and found nothing... Can someone give me a "ready" code? Please help me one more time.

const menuIconEl = $('.menu-icon');
const sidenavEl = $('.sidenav');
const sidenavCloseEl = $('.sidenav-close-icon');

function toggleClassName(el, className) {
  if (el.hasClass(className)) {
    el.removeClass(className);
  } else {
    el.addClass(className);
  }
}
menuIconEl.on('click', function() {
  toggleClassName(sidenavEl, 'active');
});
sidenavCloseEl.on('click', function() {
  toggleClassName(sidenavEl, 'active');
});

The whole code after using the Jquery works, but after each attempt to convert it to vanillaJS it no longer works.

Upvotes: 1

Views: 175

Answers (2)

somethinghere
somethinghere

Reputation: 17340

When selecting things, you can use

document.querySelector( query:String ) // returns an HTMLElement or null
document.querySelectorAll( query:String ) // returns a NodeList you can iterate over

For toggling classes, you can use classList and its methods to control classes on HTMLElements:

HTMLElement.classList.toggle( className:String, forced:Boolean|Null )

And for adding event listeners, just use addEventListener instead of on.

This turns your code into this:

const menuIconEl = document.querySelector('.menu-icon');
const sidenavEl = document.querySelector('.sidenav');
const sidenavCloseEl = document.querySelector('.sidenav-close-icon');
const onclick = e => sidenavEl.classList.toggle( 'active' );

menuIconEl.addEventListener( 'click', onclick );
sidenavCloseEl.addEventListener( 'click', onclick );

And that does it!

Upvotes: 4

Jax-p
Jax-p

Reputation: 8531

Few examples below. You might be interested in website YouMightNotNeedJquery

$('.menu-icon');
// can be replaced with:
document.querySelector('.menu-icon');
el.hasClass(className);
// can be replaced with:
el.classList.contains(className);
el.addClass(className);
// can be replaced with:
el.classList.add(className);
el.removeClass(className);
// can be replaced with:
el.classList.remove(className);

Can someone give me a "ready" code?

No. You should learn it by yourself.

Upvotes: 3

Related Questions