Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
must i use toggle class method in only jQuery or can i use it in the normal javaScript?

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 **

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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")
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!