John White
John White

Reputation: 39

Limit amount of LI and add more link

I am creating multiple lists dynamically and need to firstly limit it to 5 and then have a "More" link which should be taken from the closest previous a tag with the class .parentcat.

This is what I have so far....

HTML/JQuery

<h2><a class="parentcat" title="" href="#">Heading</a></h2>
<ul class="subcat">
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
      <li><a href="#">Link 3</a></li>
      <li><a href="#">Link 4</a></li>
      <li><a href="#">Link 5</a></li>
</ul>


$(function () {
    var link = ($(this).find('a.parentcat').attr('href'));

    $("ul.subcat").each(function () {
        $("li:gt(5)", this).hide(); /* :gt() is zero-indexed */
        $("li:nth-child(6)", this).after("<li class='more'><a href='#'>More...</a></li>"); /* :nth-child() is one-indexed */
    });
});

This limits the amount of LI's being displayed but the variable is just finding first of many a.parentcat tag it should be finding the closest a.parentcat to the UL. Also probably a very silly question who do I get the variable into the .after() all attempts I have made fail.

Upvotes: 0

Views: 318

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318558

You need to retrieve the URL inside the each loop of course. Otherwise the .attr() will always use the first element in the jQuery object.

$("ul.subcat").each(function () {
    var link = $(this).prev('h2').find('a.parentcat').attr('href');
    $("li:gt(5)", this).hide(); /* :gt() is zero-indexed */
    $("li:nth-child(6)", this).after("<li class='more'><a href='#'>More...</a></li>"); /* :nth-child() is one-indexed */
});

Upvotes: 1

Ram
Ram

Reputation: 144699

you can use each loop and store all of hrefs in an array:

var links = [];
$('a.parentcat').each(function(i, v){
   links[i] = $(this).attr('href');
})

Upvotes: 0

Related Questions