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 >
<span >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();
CodePudding user response:
Node.textContent is JavaScript, not part of the jQuery library per-se. jQuery uses the .text()
method to get the text by using textContent
under the hood. Also, read about jQuery's toggleClass() method, you can use a second boolean parameter instead, making the if
statement unnecessary.
Since you use classes it's pretty dangerous to just do $(".fav-contractors").addClass("active");
, since you could:
- have many
.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
- Use
.each()
to iterate all your elements of a specific class - Use
.closest()
to traverse to a specific element ancestor (or self) - (As already mentioned) use
toggleClass()
$(".fav-con-count").each(function() {
$(this).closest(".fav-contractors").toggleClass("active", $(this).text() > 0);
});
.fav-contractors { padding: 1rem; }
.active { background: gold; }
<span >
<span >7</span>
</span>
<span >
<span >0</span>
</span>
<span >
<span >3</span>
</span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
CodePudding user response:
You should use .text()
instead of textContent
function favCounter() {
if ($(".fav-con-count").text() > 0) {
$(".fav-contractors").addClass("active");
}
};
favCounter();
.active {
background: yellow;
}
<span >
<span >7</span>
</span>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
This is an example of the number 0 not adding the active class
function favCounter() {
if ($(".fav-con-count").text() > 0) {
$(".fav-contractors").addClass("active");
}
};
favCounter();
.active {
background: yellow;
}
<span >
<span >0</span>
</span>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>