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

123
Views
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 answers
Answer question

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