Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using :visible and :first-child together in jQuery

Tags:

jquery

I'm trying to use the ":visible" and ":first-child" pseudo-selectors together in jQuery and it doesn't seem to be working out. I have the following HTML:

<div>
    <a class="action" style="display:none;">Item One</a>
    <a class="action">Item One</a>
    <a class="action">Item One</a>
</div>

And the following jQuery call:

$("div a.action:visible:first-child").addClass("first");

But it never seems to find the right element...it finds the first element but not the first visible element. I've even tried swapping the selector order ":first-child:visible" instead of ":visible:first-child" and that doesn't work either. Any ideas?

like image 675
JC Grubbs Avatar asked May 06 '09 16:05

JC Grubbs


2 Answers

Your selector

$("div a.action:visible:first-child").addClass("first");

matches only the A element only when it's the first-child of the parent DIV and when it is visible.

If you want to get the first visible A element, you should use the .eq function

$("div a.action:visible").eq(0).addClass("first");

or the :first pseudo-class

$("div a.action:visible:first").addClass("first");
like image 104
Rafael Avatar answered Nov 15 '22 22:11

Rafael


I'm not sure why :visible:first-child isn't working, but you can try

$("div a.action:visible").eq(0).addClass("first");
like image 30
Kobi Avatar answered Nov 15 '22 22:11

Kobi