Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
is it possible to using hasClass() with querySelectorAll()?

I just start learning javascript and jquery, I tried to add and remove classes with this code

 if ($(".head").hasClass("collapsed")) {
  $(".fas").addClass("fa-chevron-down");
  $(".fas").removeClass("fa-chevron-up");
 } else {
  $(".fas").addClass("fa-chevron-up");
  $(".fas").removeClass("fa-chevron-down");
 }

But the code is to add/remove classes at once to all .head when I click on a particular .head I want to add/remove the classes.

Also I tried to using querySelectorAll() on code below but appear to be an error with waring messages "jQuery.Deferred exception: x[i].hasClass is not a function TypeError: x[i].hasClass is not a function" and "Uncaught TypeError: x[i].hasClass is not a function"

var x = document.querySelectorAll(".head");

for (var i = 0; i < x.length; i++) {

 if (x.hasClass("collapsed")) {
  $(".fas").addClass("fa-chevron-down");
  $(".fas").removeClass("fa-chevron-up");
 } else {
  $(".fas").addClass("fa-chevron-up");
  $(".fas").removeClass("fa-chevron-down");
 }
}

is it not possible to use querySelectorAll() together with hasClass()?
if it's possible, how to use it or is there an alternative solution to my issue?

Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In your code x is a NodeList and it does not have hasClass. Also x.hasClass is wrong as you want to access each element of the collection`.

You can try by $(x[i]).hasClass

Else you can do document.querySelectorAll(".head.collapsed")

var x = document.querySelectorAll(".head.collapsed").forEach((item) => {
  item.classList.add('customClass')

})
.customClass {
  color: green
}
<div class="head collapsed"> Test1</div>
<div class="head"> Test2</div>
<div class="head collapsed"> Test3</div>
<div class="head"> Test4</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda