Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda