Utilizing jQuery to toggle nested divs within identical parent divs when they contain more than three elements using the :nth-child selector

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.

Answer №1

Here's a trick you can use:

$(".parent").each(function() {
  $(this).find(".child:gt(2)").hide();
});
$(".showhide").click(function() {
  $(this).prev().find(".child:gt(2)").slideToggle();
});

Check it out on Fiddle

The .gt() selector targets elements with an index greater than the specified parameter.

If you want to update the text after toggling, you can do so with this code:

$(".parent").each(function() {
  $(this).find(".child:gt(2)").hide();
});
$(".showhide").click(function() {
  var obj = this;
  $(this).prev().find(".child:gt(2)").slideToggle(function() {
    if ($(this).is(":visible"))
      $(obj).text("hide");
    else
      $(obj).text("show more");
  });
});

Updated Fiddle

Remember, utilizing the callback function of slideToggle is essential for updating the text since slideToggle operates asynchronously.

View the Final Changes on Fiddle

Answer №2

If you want to conceal it using CSS, you can do so with the following code:

.parent div:nth-child(n+4) {
  display: none;
}

Additionally, you can utilize jQuery to toggle the class and manage its visibility.

$('.parent').filter(function(){
  return $(this).children().length <= 2;
}).next('.showhide').hide();


$('.showhide').click(function() {
  $(this).text(function(i, txt) {
    console.log(txt);
    return txt === "Show"  ? "Hide" : "Show";
  });
  $(this).prev('.parent').find('div:hidden, div.show').toggleClass('show').stop().slideToggle();
});
span {
  cursor: pointer;
}
.parent div:nth-child(n+4) {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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</span>

<div class="parent">
  <div class="child">1</div>
  <div class="child">2</div>
</div>
<span class="showhide">Show</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</span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding margin to an HTML element causes the entire page to shift downward

Despite successfully applying margin to other elements, I encountered an issue with #searchbarcontainer where it causes the entire page to shift downward. My goal is to center it slightly below the middle of the page, but I'm struggling to find a solu ...

Adjusting images of various sizes within a single row to fit accordingly

I am faced with a challenge of aligning a set of images on a webpage, each with varying heights, widths, and aspect ratios. My goal is to arrange them in a way that they fit seamlessly across the screen while ensuring their heights are uniform. Adjusting ...

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

Guide to aligning 2 divs side by side using bootstrap

I have been experimenting with different methods like col-xs-6 for the first child, but I can't seem to get it right. How can I achieve this layout using only Bootstrap? Despite trying col-xs-6, I still haven't been able to place these divs next ...

saving user's scroll position in a Vue 3 app

Encountering an issue with my Vue application. It comprises more than 40 pages, and the problem lies in the browser caching the scroll position. As a result, when users navigate from one page to another, the browser displays the scroll position of the prev ...

How can we optimize ternary statements within ternary statements in Type Script and React Native for best practices?

Can you help me optimize this code snippet that uses nested ternary operators for better readability and correctness? <TouchableOpacity style={ darkMode ? filterState === 'A' ? styles.activeButtonDark : styles.buttonDa ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

IE7 is not applying the conditional CSS styles to content loaded through AJAX

I am currently tackling some challenges with IE7 compatibility in a Rails application that I am developing. It appears that CSS styles implemented from a stylesheet applied with a conditional comment are not being rendered properly when using HAML like thi ...

Trouble with Bootstrap 5 Dropdown Functionality

Currently, I am using Bootstrap 5 in conjunction with Django to create a website and I'm encountering difficulties with getting a dropdown feature to work properly. Despite copying the code directly from w3schools, it fails to function when I load the ...

Transform the selected component in Material-UI from being a function to a class

Hello, I am currently learning about React and I have started using the select button from material-ui. The code I found on the material ui page is for a functional component, but I am more comfortable with class components. Here is the code snippet provid ...

Creating dynamic color changes with overlapping SVG triangles using CSS

I'm facing a challenging issue: I want to change the color of an SVG line as it intersects with a triangular background created using CSS. Although I've experimented with gradients, they don't produce the desired effect. My goal is for the ...

Is it feasible to evaluate a Typescript method parameter decorator at request time in a nodejs+nestjs environment rather than just at build time?

Looking to simplify my handling of mongodb calls with and without transactions in a single service method by writing a decorator. This would help eliminate the repetition of code and make things more efficient. Key points for usage: • Service class has ...

Executing multiple AJAX requests with promises in Angular based on an array of values

I have been working on implementing multiple ajax calls in sequence using Angular. Interestingly, everything seems to be working fine when I use $.ajax, but when I switch to using $http for server requests in Angular, things start to go awry. Both methods ...

Form must transmit data to a controller in codeigniter

I'm currently working on a form that needs to post data to a function within the controller. The form contains two buttons that should send data to two different controller functions. Below is the HTML code for the form: <form> <input id="am ...

Live Server in VS Code not refreshing automatically as expected

My problem is with VS Code and Live Server for HTML CSS. I expected the page to automatically reload after editing my HTML, but that's not happening. Even though I have Auto-Save enabled, Live Server isn't updating or refreshing my page automati ...

Switch up the current Slick Carousel display by utilizing a div element

We have implemented the slick carousel to show only one slide at a time within the <div class='item__wrapper'>. Beneath this are three items, and we want the slick carousel to update when any of these items are clicked. Issues Using item ...

Having Difficulty with Mathematical Operators in AngularJS

Here is the code snippet I am currently working with: $scope.calculateTotal = function() { $scope.totalAmounts = []; var total = 0; for (var i = 0; i < $scope.orderDetails.length; i++) { console.log($scope.orderDetails[i]['pric ...

The `Route` component is expecting a `function` for the `component` prop, but instead it received an `object`

For a while now, I've been grappling with an issue that seems to be unique to me. The problem lies within my component and container setup for the start screen rendering at the initial route. components/DifficultySelection.jsx import React from &apo ...

Removing the active class from a Bootstrap menu can be achieved by targeting the specific

I have successfully implemented a Bootstrap Menu by placing it in a separate header.html file and using the php include function to call that file on every page of my website. However, I am now trying to figure out how to dynamically change the active cl ...

What is the reason for AngularJS not utilizing the most recently assigned value?

<html> <head> <title>Test</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="angul ...