1

I have the following structure:

<div class="myClass">1</div>
<div class="myClass">2</div>

How can I select the first element matched by .myClass?

I know that I can do: [PARENT OF .myClass] .myClass:first-child {/* rules */} but I am curious if there is a pseudo CSS class that selects the first element matched by the selector.

Is that possible? How?

The jQuery selector would look like this: .myClass:first, but :first seems not to work in CSS.

2
  • If there aren't more groups of the same class, and if the first is the first child of a parent, you can use first-child, otherwise there is the nth-child, which is somewhat more customizable, or the nth-of-type selector that isn't supported in all older browsers. Commented Nov 30, 2013 at 19:26
  • Given that you have jQuery, why not $('.myClass:first') or $('.myClass').first() (or other variations thereof)? Or, in plain JavaScript: document.querySelector('.myClass')? Commented Nov 30, 2013 at 23:32

3 Answers 3

1

Okay, I'm not sure, but this might work for you.

some.great-selector:first-of-type {
  /* Your rules here */
}

This will match only first child that matches some.great-selector in each parent node. This is somewhat different from what :first does in JQuery, but might be still useful, e.g. in conjunction with parent > selector.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use:

.myClass:first-of-type {
      background-color:#233423;
      color:#FFFFFF;
    }

http://jsfiddle.net/65adr/44/

or you can give a look here for other alternatives:

http://reference.sitepoint.com/css/css3psuedoclasses

Comments

0

:first-child is the closest you will get. Though it is well supported if you're looking for something that will work in legacy browsers.

If you want to achieve support in legacy browsers you can apply a style to all elements with a particular class name and then remove it for all sibling classes as so:

.my-class {
  border-top: 1px solid lightgray;
  border-bottom: 1px solid lightgray;
}

.my-class + .my-class {
  border-top: none;
}

A rather arbitrary example but you'll get the point.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.