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');
});
$('ul li').not(':first-child').each(function ()
{
var bigImage = $(this).find('a.main-img').attr('href');
$('<img/>').attr('src', bigImage).appendTo('#banner-holder');
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With