designerNProgrammer
designerNProgrammer

Reputation: 2701

selecting an image from a list of images within same class

i am trying to make a carousel here.

here is my markup

<img  class="fullBg anim" src="img/bgs/1.jpg" >
<img  class="fullBg anim" src="img/bgs/2.jpg" >
<img  class="fullBg anim" src="img/bgs/3.jpg" >
<img  class="fullBg anim" src="img/bgs/4.jpg" >

Now i want to select the first image or the second image of the class without giving each image an id. Please tell me how to do that. I tried the n-th child but it didnt work. thanks.

Upvotes: 2

Views: 642

Answers (7)

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can use eq() method with index starting from 0 , use negative value for select from end

$('img.fullBg').eq(0)//select first image

Fiddle Demo

The above example select first image , for secong change 0 to 1

Documentation

Upvotes: 1

amarano
amarano

Reputation: 76

For the first element:

$('.fullBg').eq(0);

Upvotes: 1

Felix
Felix

Reputation: 38102

You can use:

$('.fullBg').each(function() {
    // $(this) here will target each of your image with class fullBg 
});

If you want to target first image, you can use:

$('img.fullBg:eq(0)');

You can use :nth-child() here, but you need to wrap your images inside a div, for example:

<div class="test">
    <img  class="fullBg anim" src="img/bgs/1.jpg" >
    <img  class="fullBg anim" src="img/bgs/2.jpg" >
    <img  class="fullBg anim" src="img/bgs/3.jpg" >
    <img  class="fullBg anim" src="img/bgs/4.jpg" >
</div>

then you can use:

$(".test img:nth-child(1)")

to target your first image or:

$(".test img:nth-child(2)")

to target your second image.

Upvotes: 1

Steve Claridge
Steve Claridge

Reputation: 11080

Something like this would work (not tested), it removes the first from the list and adds it to the end:

setInterval(function() { 
          $('#slidediv > div:first')
            .fadeOut(1000)
            .next()
            .fadeIn(1000)
            .end()
            .appendTo('#slidediv');
        },  5000);

You'd need to wrap your tags in a div called #slidediv

Upvotes: 1

Kawinesh S K
Kawinesh S K

Reputation: 3220

Just have your own css selector and give your own number instead of (2)

selector:nth-of-type(2)

DEMO

Upvotes: 1

Anton
Anton

Reputation: 32581

You can use :eq() to select 1st,2nd etc..

$('img.fullBg:eq(1)'); //selects 2nd image

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

You need to wrap that html in parent element like div. Then try:

$(parentselector).find("img:eq(1)");//for second image
$(parentselector).find("img:eq(0)");//for first image

Upvotes: 1

Related Questions