0

I've got a div with a number of image + text divs, the images and text divs appear in a random order, it could be image-image-text-image or text-image-text-image etc... each text item has a class associated with it, so how do I target the nth element of that class?

I can't target the parent as the first item may be an image or text and I only want to target each text item individually. This is the class applied to the variable number of divs in a variable order:

.article_content_divs {
    width:720px;
    float:left;
    margin-left:5px;
    margin-top:5px;
    text-align:justify;
}
Crizly
  • 971
  • 1
  • 12
  • 33

1 Answers1

0

You can use :nth-of-type(n). However, that requires you to use different types rather than different classes.

So instead of have <div class="image"> and <div class="text">, you would need to have <div class="image"> and <p class="text"> for instance (or simply <div> and <p>, that's all that matters).

Then you can use selectorforparent p:nth-of-type(n).

Note that nth-of-type is relatively recent, so you'll have to check backwards compatibility.

jcaron
  • 17,302
  • 6
  • 32
  • 46
  • It doesn't seem to be working on safari mac – Crizly Jul 02 '14 at 23:32
  • Works here. Not that your text and image elements must be different types (e.g. `p` vs `img`, or `p` vs `div`, or anything else you fancy), and you must include the type in the selector: `p:nth-of-type(3)` – jcaron Jul 02 '14 at 23:36
  • he does not target types here, he wants to target ***classes***, that's why it does not work. – King King Jul 02 '14 at 23:43