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