Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip first list item while iterating over the unordered list. JQuery

I have an unordered list where the list items contain links to images. My code currently iterates over the list items, gets the href, creates a new image container within the div banner-holder and adds the src property.

What I want to do is skip the first list item as I already have that image within the banner-holder and I do not want to add it twice.

Thank you.

$('li').each(function ()
    {
        var bigImage = $(this).find('a.main-img').attr('href');

        $('<img/>').attr('src', bigImage).appendTo('#banner-holder');

    });
like image 817
Cecil Theodore Avatar asked Feb 03 '26 12:02

Cecil Theodore


2 Answers

$('ul li').not(':first-child').each(function ()
    {
        var bigImage = $(this).find('a.main-img').attr('href');

        $('<img/>').attr('src', bigImage).appendTo('#banner-holder');

    });
like image 138
danludwig Avatar answered Feb 06 '26 09:02

danludwig


The jQuery each method passes the index of the current item, so you could use that:

$('li').each(function (index)
{
    if (index > 0) { 
        var bigImage = $(this).find('a.main-img').attr('href');

        $('<img/>').attr('src', bigImage).appendTo('#banner-holder');
    }
});

Or, you could do it with the gt selector:

$('li:gt(0)').each(function() {
    ...
});

The current jQuery documentation has this note about the gt selector:

Because :gt() is a jQuery extension and not part of the CSS specification, queries using :gt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(index) instead.

like image 34
FishBasketGordo Avatar answered Feb 06 '26 09:02

FishBasketGordo