Within my HTML markup, I have created two parent div
elements that are exactly the same but contain different content. My goal is to have a functionality where if a parent div
has more than 3 child div
elements, a "show more" text will be displayed at the end of the div
, allowing users to see the hidden child div
elements by clicking on it. As a beginner in JavaScript and jQuery, I am struggling with understanding selectors. Below is my code:
<div class="parent">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
</div>
<span class="showhide">Show-hide</span>
<div class="parent">
<div class="child">1</div>
<div class="child">2</div>
</div>
<span class="showhide">Show-hide</span>
<div class="parent">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
</div>
<span class="showhide">Show-hide</span>
the expected result should look like this:
1
2
3
show-hide
1
2
1
2
3
show-hide
Below is the script I'm using:
$('.parent div:nth-child(n+4)').hide();
var l = $('.parent div').length;
if (l > 3) {
$('.showhide').show();
} else {
$('.showhide').hide();
}
$(".showhide").click(function() {
$this.find(".parent div:nth-child(n+4)").toggle('slide');
});
Currently, only the initial part of the code is functional which hides the div
elements beyond the first three within each parent div
. However, implementing the hiding text and toggling feature is not working as intended.
I have experimented with various alterations such as placing the span
element inside the parent div
, modifying the selectors to use .closest
, and attempting to utilize :gt()
instead of :nth-child
, but none of these solutions have produced the desired outcome.