Home > Blockchain >  must i use toggle class method in only jQuery or can i use it in the normal javaScript?
must i use toggle class method in only jQuery or can i use it in the normal javaScript?

Time:01-03

i have a multi section landing page project and i want to add an icon of hambuger in a specific media query when i click on it it displays the navbar elements in a block and when i click it again it disappears >>> my proplem is when i use toggle class method it doesnt toggle class and it doesnt work even when i test it in my console

#My Code#

function myfunction() {
  const lis = document.querySelectorAll("li");
  const ul = document.querySelector("ul");
  const icon=document.querySelector("fa fa-bars"); 
  icon.addEventListener("click",()=>{
    lis.classList.toggle("lessSize");
  })
  
}

**Note: idont wanna use the library jQuery in this iwant to make it without it **

CodePudding user response:

classList.toggle() will work fine. Your code is not working for two reasons.

Firstly, fa fa-bars is not a valid selector. I would presume you mean to use document.querySelector('.fa.fa-bars') instead.

Secondly, querySelectorAll() returns a NodeList, not a single element. As such you need to loop through them and call classList.toggle() on each individual element.

With those changes made the correct code should look like this:

function myfunction() {
  const lis = document.querySelectorAll("li");
  const ul = document.querySelector("ul");
  const icon = document.querySelector(".fa.fa-bars");
  
  icon.addEventListener("click", () => {
    lis.forEach(li => li.classList.toggle('lessSize'));
  })
}

Note that this example is assuming your use of querySelector() to retrieve the .fa-bars element is correct, and that there is only 1 of those elements in the DOM. If there is multiple then you will need another loop there too.

CodePudding user response:

Apart from the answer from the comment, this will not work because you are targeting many list items with

const lis = document.querySelectorAll("li");

so this class will be toggled only on the first list item found, you should loop over them like so:

lis.forEeach(li => {
   li.classList.toggle("lessSize")
})
  • Related