Reputation: 2947
I have a HTML which is receive input from users. My job is to count cards they enter and style these cards. Cards are placed inside <section>
.
Problems: My Jquery is only counting and works well in one section. If users enter more than one sections, the code doesn't work. My code below shows when users enter 2 sections: cards in first section should be blue and cards in second section should be red, but now they are all blue.
var numCard = $('.cards').length;
if (numCard == "2") {
/* $('.cards').css('color', 'red'); */
$("section .cards").parent().addClass("two-cards");
} else if (numCard == "3") {
$("section .cards").parent().addClass("three-cards");
} else {
$('section .cards').parent().addClass("four-cards");
}
body {
padding: 20px;
font-family: Helvetica;
}
.two-cards .cards {
color: red;
}
.three-cards .cards {
color: green;
}
.four-cards .cards {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
<div class="cards">
Third Card
</div>
<div class="cards">
Third Card
</div>
</section>
<p>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
</section>
Upvotes: 4
Views: 366
Reputation: 67505
You need to loop through the sections, then use this
keyword to check :
$('section').each(function() {
var numCard = $('.cards', this).length;
if (numCard == "2") {
$(this).addClass("two-cards");
} else if (numCard == "3") {
$(this).addClass("three-cards");
} else {
$(this).addClass("four-cards");
}
});
body {
padding: 20px;
font-family: Helvetica;
}
.two-cards .cards {
color: red;
}
.three-cards .cards {
color: green;
}
.four-cards .cards {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
<div class="cards">
Third Card
</div>
<div class="cards">
Third Card
</div>
</section>
<p>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
</section>
</p>
Upvotes: 1