a13ks a13ks - 1 year ago 83
HTML Question

jQuery eq() selector not working

I tried every possible combination that I could find but it still doesn't work. trying to select the first, second, third ... image and change it's css properties.
The javascript :


The html :

<div id = "slider">
<img id = "slider_img5" class = "slider_image" src = "img/slider_image_5.png" width = "1000px" height = "400px" alt = "slider_image_5">
<img id = "slider_img4" class = "slider_image" src = "img/slider_image_4.png" width = "1000px" height = "400px" alt = "slider_image_4">
<img id = "slider_img3" class = "slider_image" src = "img/slider_image_3.png" width = "1000px" height = "400px" alt = "slider_image_3">
<img id = "slider_img2" class = "slider_image" src = "img/slider_image_2.png" width = "1000px" height = "400px" alt = "slider_image_2">
<img id = "slider_img1" class = "slider_image" src = "img/slider_image_1.png" width = "1000px" height = "400px" alt = "slider_image_1">

The css:

position : absolute;
height : 400px;
width : 100%;
border-radius : 3px;
-moz-border-radius : 3px;
box-shadow : 1px 1px 5px #bbbbbb;
-moz-box-shadow : 1px 1px 5px #bbbbbb;

position : absolute;
top : 0px;
left : 0px;
border-radius : 3px;
-moz-border-radius : 3px;

#slider_img1 , #slider_img2 , #slider_img3 , #slider_img4{
visibility : hidden;
display : none;

I hope someone can help me.

Thank you for all the answers but none of them work. I'm calling the function on document ready and it is definitely called (tested with alert(); ) . I also preset the styles of all images so they are all hidden except for the first one.

Sorry guys, there was a semicolon missing. Thank you for all the help!

Answer Source

You need a space between #slider and :eq(0).

Without the space, it's looking for an element #slider that is the first, instead of the first descendant of #slider.

Note however, that :eq is a jQuery extension to selectors. For better performance you should use $('#slider img').eq(n), allowing the entire (valid) CSS selector to be parsed as quickly as possible, and then using .eq to get the element you want.

Alternatively, use the native CSS :nth-child() syntax instead, i.e. #slider :nth-child(1), but note that this uses numbers starting from 1 instead of 0.

Also, your filter(img) syntax as given is incorrect. It should be chained (i.e. .filter) and the parameter should be a valid selector, i.e. 'img' (with the quotes). However if your real HTML is as shown you don't need the filter because it's a NoOp - the previous function call can only return images.