I want to add class "active" to "fav-contractors" container only when number inside "fav-con-count" span is greater than 0.
This is HTML code
<span class="fav-contractors">
<span class="fav-con-count">7</span>
</span>
and this is jQuery code
function favCounter() {
if ($(".fav-con-count").textContent > 0) {
$(".fav-contractors").addClass("active");
}
};
favCounter();
Which "if" rule should I use? I also tried something like that but it didn’t work:
function favCounter() {
var favValue = $(".fav-con-count").textContent;
if (+favValue > 0)) {
$(".fav-contractors").addClass("active");
}
};
favCounter();
2
Answers
You should use
.text()
instead oftextContent
This is an example of the number 0 not adding the active class
Node.textContent is JavaScript, not part of the jQuery library per-se. jQuery uses the
.text()
method to get the text by usingtextContent
under the hood. Also, read about jQuery’s toggleClass() method, you can use a second boolean parameter instead, making theif
statement unnecessary.Since you use classes it’s pretty dangerous to just do
$(".fav-contractors").addClass("active");
, since you could:.fav-contractors
Elements in a single page and all will get the active class$(".fav-con-count").text() > 0
means that only if the first of that class Element has text greater than 0 – which might also be incorrect and lead to a buggy undesired behavior.Solution
.each()
to iterate all your elements of a specific class.closest()
to traverse to a specific element ancestor (or self)toggleClass()