0

I want to write a CSS selector which matches the first occurrence of an element with class "icon". The elements haven't got a common parent (as seen below), so the :first-child or :first-of-type pseudos didn't work for me.

The HTML markup isn't very good, but its specification, so it's not possible to change it.

Is there any CSS only solution, to match the first occurence of an element?

<div>
    <div class="icon"></div> <!-- only this should be matched -->
    <p class="categoryTitle">Category 1</p>
    <ul>..</ul>
</div>
<div>
    <div class="icon"></div>
    <p class="categoryTitle">Category 1</p>
    <ul>..</ul>
</div>
<div>
    <div class="icon"></div>
    <p class="categoryTitle">Category 1</p>
    <ul>..</ul>
</div>

OR

<div>
  <!-- nothing here --> 
</div>
<div>
    <div class="icon"></div>  <!-- only this should be matched -->
    <p class="categoryTitle">Category 1</p>
    <ul>..</ul>
</div>
<div>
    <div class="icon"></div>
    <p class="categoryTitle">Category 1</p>
    <ul>..</ul>
</div>

OR

<div>
  <!-- nothing here --> 
</div>
<div>
  <!-- nothing here too -->
</div>
<div>
    <div class="icon"></div>  <!-- only this should be matched -->
    <p class="categoryTitle">Category 1</p>
    <ul>..</ul>
</div>
thirtydot
  • 224,678
  • 48
  • 389
  • 349
rootless
  • 139
  • 12
  • If you could add some js code, then you could use that to change the element's style. Otherwise, without changing the html itself in some way (like adding an id to the first icon, or some other way), I don't see a way to do this. – Eran Zimmerman Gonen Aug 22 '11 at 09:14
  • Might also be related: http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class – Eran Zimmerman Gonen Aug 22 '11 at 09:23

2 Answers2

1

No, there isn't. You'd have to find out which of the parent div elements have .icon children in the first place, which you can't do with CSS selectors. The jQuery selector .icon:first does exactly what you want, but :first is not part of CSS.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Well, the problem lies more in navigating the `.icon` elements' hierarchies than finding out which `div`s have `.icons`, but you get the idea... – BoltClock Aug 22 '11 at 09:16
  • It's just not possible with that setup, i accept that. We now have a class "loaded" on a container div, when it gets content. Now a selector like this is possible: "div.loaded:nth-of-type(2) .icon" – rootless Aug 22 '11 at 10:00
0

I'd say you'll have to use some sort of javascript to do this. I've actually just done this on a project of my own.

jQuery:

$('.Icon:first').addClass('myclass'); // or .css('attribute', 'value') depending on what you want.

The above script will at all times ONLY affect the first match of .Icon it finds.

I know it's not CSS, but you can't really do what you want to achieve by only using CSS.