Switch list items with more than a quantity of 3

I have a set of unordered list items that I want to display only the first 3 li elements for each when loading. Upon clicking the + sign, the remaining list items should toggle visibility for just that specific list group. While this can potentially be achieved with CSS alone, I am currently working on implementing it using jQuery.

Here is how I have set it up:

HTML

<div class="container">
<div class="col-lg-3">
  <div class="toggle" tabindex="1">
    <p class="header" onclick="void(0)">LINK</p>
    <ul>
      <li>link 1</li>
      <li>link 2</li>
      <li>link 3</li>
      <li>link 4</li>
      <li>link 5</li>
      <li>link 6</li>
    </ul>
  </div>
</div>

<div class="col-lg-3">
  <div class="toggle" tabindex="1">
    <p class="header" onclick="void(0)">LINK</p>
    <ul>
      <li>link 1</li>
      <li>link 2</li>
      <li>link 3</li>
      <li>link 4</li>
      <li>link 5</li>
      <li>link 6</li>
    </ul>
  </div>
</div>

<div class="col-lg-3">
  <div class="toggle" tabindex="1">
    <p class="header" onclick="void(0)">LINK</p>
    <ul>
      <li>link 1</li>
      <li>link 2</li>
      <li>link 3</li>
      <li>link 4</li>
      <li>link 5</li>
      <li>link 6</li>
    </ul>
  </div>
</div>
</div>

jQuery

$('ul li').hide().filter(':lt(3)').show();
$('ul').append('<li>+</li>').find('li:last').click(function() {
  $(this).siblings(':gt(2)').toggle();
});

JSFIDDLE: LINK

Answer №1

To modify the initial line of jQuery, you can simply do the following:

$('ul').each(function() {
  $('li:gt(2)', this).hide()
});

Check out this jsFiddle demo

$('ul').each(function() {
  $('li:gt(2)', this).hide()
});
$('ul').append('<li>+</li>').find('li:last').click(function() {
  $(this).siblings(':gt(2)').toggle();
});
ul li {
  list-style-type: none;
}

.container {
  display: flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="container">
  <div class="col-lg-3">
    <div class="toggle" tabindex="1">
      <p class="header" onclick="void(0)">CLICK HERE</p>
      <ul>
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
        <li>item 5</li>
        <li>item 6</li>
      </ul>
    </div>
  </div>

  <div class="col-lg-3">
    <div class="toggle" tabindex="1">
      <p class="header" onclick="void(0)">CLICK HERE</p>
      <ul>
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
        <li>item 5</li>
        <li>item 6</li>
      </ul>
    </div>
  </div>

  <div class="col-lg-3">
    <div class="toggle" tabindex="1">
      <p class="header" onclick="void(0)">CLICK HERE</p>
      <ul>
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
        <li>item 5</li>
        <li>item 6</li>
      </ul>
    </div>
  </div>
</div>

Answer №2

The selection of elements using the :gt() selector is limited to the first 3 li elements within the initial ul.


To achieve a similar effect, here are two alternative methods:

Method 1: Using CSS :nth-child() pseudo-class with :not() to exclude the last element in the list:

ul li:nth-child(n+4):not(:last-child) {
  display: none;
}

Method 2: With jQuery, utilizing the :nth-child() pseudo-class selector.

$('ul li:nth-child(n+4)').hide();

You can also implement your custom toggling functionality like this:

$('ul li:nth-child(n+4)').hide();
$('ul').append('<li>+</li>').find('li:last').click(function() {
  $(this).siblings(':gt(2)').toggle();
});
ul li {
  list-style-type: none;
}

.container {
  display: flex;
}

Answer №3

$('ul').each(function(){
  $(this).find('li').hide().filter(':lt(3)').show();
});

Give this a try!

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

When clicked, the menu disappears successfully with the "show" functionality, but unfortunately, the "hide" feature is not working as intended

Within my menu, I have a section for portfolios that transforms into a dropdown on desktop hover and mobile click. The issue arises on mobile devices where the first click displays the menu correctly, but subsequent clicks do not trigger any change. I att ...

What could be causing my content to unexpectedly break out of its designated div structure?

My website on Wordpress is causing me trouble. When I input text directly into the HTML/CSS structure hardcoded style, it fits perfectly. However, when I attempt to do the same thing using Wordpress <?php echo the_content();?>, it ends up breaking ou ...

Is it possible to use Highcharts in AngularJs without jQuery?

Is there a way to use Highcharts without relying on the full jQuery library? The current popular option seems to require jQuery, but I'm having trouble getting it to work without it: https://github.com/pablojim/highcharts-ng Can I develop a Highchart ...

Implementing a clickable image using an anchor tag in JavaScript

I need to enhance my image tag in JQuery by adding an anchor tag alongside it. How can I accomplish this using JavaScript? Here is what I attempted: var imgg = document.createElement("img"); imgg.className='myclass'; $( ".myclass" ).add( "<a ...

Do AJAX-inserted elements cause a delay in the loading of the DOM? How is the loading of the DOM determined

Is the loading time of the DOM delayed if a page executes Javascript upon loading which inserts new elements via AJAX? Our UI relies on jQuery's "ready" function to function after the DOM is loaded, and we hoped that inserting page elements asynchron ...

We'll show you the steps to properly organize a set of radio buttons created dynamically within a 'controlgroup' using jQuery Mobile

I am facing an issue with grouping dynamically generated radio buttons into a jQuery Mobile control group. I generate the radio buttons and append them to a div, but they are displayed separately even though the wrapping div contains a 'controlgroup&a ...

Is there a way to send the id to the print page within the ajax success function?

https://i.stack.imgur.com/SGAAT.jpg The image above shows the selection of 3 records with MR No 7, 8, and 9. These selected records were successfully inserted into my database. Now, I need to retrieve these IDs in the ajax success function to pass them to ...

It appears that Javascript variables are behaving in a static manner

I am currently building a PHP website with a registration page for users. I am implementing the LOOPJ jQuery Autocomplete script from to enable users to select their country easily. In this process, I encountered an issue where the value of another field ...

Checking if an array exists after parsing JSON using jQuery

I am working on a solution to automatically submit form fields after triggering the onchange event. After making some changes, the JSON response I receive appears in this format: { "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error" } ] } ...

JavaScript drop-down menu malfunctioning

I am currently in the process of learning web development languages, and I'm attempting to create a dropdown list using JavaScript (I previously tried in CSS without success). I would greatly appreciate it if you could review my code and let me know ...

Attention: Vanishing within specified time limit

Can you help me find a technology that will display a warning message and make it disappear with a nice effect over a set amount of time? I think AJAX or JavaScript might be able to achieve this. The warning message I'm currently using is: <scrip ...

The issue of Jquery not functioning properly within Ajax-included HTML documents

I've tried looking at some other posts, but I couldn't understand them. The jQuery works fine when the page is loaded, but when the same elements are loaded from an AJAX script, the jQuery doesn't work. I know I need to do a callback, but ca ...

The functionality of AngularJs' scope.apply appears to interfere with the autocomplete feature of jQuery UI

I'm having difficulty implementing an autocomplete field into a directive using Jquery-UI. Let me explain. Here is my html element : <div class="form-group" > <input type="text" placeholder="Find a category" data-category-autocomplete dat ...

Making <div> elements responsive by rearranging their display order using CSS in media queries, troubleshooting issues with floats, and adjusting font sizes

I'm currently working on a webpage located at: On this page, there is a containing division with 5 elements inside. They are floated left in order to align vertically, but I am facing some challenges when it comes to adjusting my CSS for media querie ...

Set a unique class for several elements depending on a given condition

Is there a way to assign a color class based on the element's value without looping through all elements? Check out my jsfiddle HTML <div> <ul> <li class="MyScore">90</li> <li class="MyScore"> ...

Issues encountered with JavaScript when trying to use the jQuery API

I'm trying to fetch random quotes using a Mashape API, but when I click the button, nothing happens. I've included the JS and HTML code below. Can anyone spot an issue with the JS code? The quote is not displaying in the div. Thank you! $(' ...

<v-time-picker> - issue with time selection

<v-time-picker> - Are you certain that the component was properly registered? If dealing with recursive components, remember to include the "name" option <div class="form-inline"> <label for="">Time</label> <v-time-pick ...

Revamp your Redux Form with a fresh new 'Field' label style

Is there a way to style the label of a Redux Form field? The Redux Form API does not provide information on how to apply styles to the label. Despite applying the classes.formField class, the label itself remains unstyled. Could this be an issue with inhe ...

Utilizing HTML's multiple input type color feature to save selected colors directly to the database

I am currently using the input type color to select colors for customizing my site. I save the selected color to a database and then retrieve it to apply it to different areas of the site. This works well for a single input type color, but now I have mul ...

What is the fastest way to add an email subscription form to my website without needing to configure a database?

Would it be possible to integrate a sign-up text box on our site for users interested in receiving launch notifications? Any suggestions on the most effective method to implement this feature? EDIT: Our current use of Prefinery has limitations as we cann ...