9

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?

1
  • why do you need a first-child here? May 6, 2009 at 16:51

4 Answers 4

31

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");
4

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

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

As far as I know the pseudo-class selector :first-child will only match the first child ever. It can not be further specified by adding a pseudo-class that it must also be visible. You might want to try writing

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

instead of using the proper css pseudo-class. JQuery documentation for :first

1

You might want to try $( "div a.action:visible(:first-child)) as your selector, that is how jQuery specifies using multiple psuedo-selectors in its API documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.