3

I have the following structure:

<div id="wrapper">
  <div></div>
  <div></div>
  <div itemprop="description"></div>
</div>
<div itemprop="description"></div>
<div></div>
<div></div>

How to select only the first div with itemprops=description? Or how to select the 3rd div inside #wrapper div?

connexo
  • 53,704
  • 14
  • 91
  • 128
Gorna-Bania
  • 215
  • 1
  • 2
  • 9

3 Answers3

3

If you can, add a class to the element you wish to target, e.g.:

<div id="wrapper">
    <div></div>
    <div></div>
    <div class="{{target-class}}" itemprop="description"></div>
    <div itemprop="description"></div>
    <div></div>
</div>

Then use your "target" class name to select the relevant element. Its much cleaner and will cover you in the case of changes to the DOM.

I wouldn't advice targeting an element using nth-child unless you are targeting an element exclusively because it is the nth element.

An alternative would be to target the element by targeting all elements after it, e.g.

[itemprop="description"] {
    /* targeted */
}
[itemprop="description"] ~ [itemprop="description"] {
    /* not targeted */
}

You can see an example of that working here

Alexander Holman
  • 929
  • 9
  • 21
1

For this specific case:

#wrapper > div:nth-child(3)

Though if the markup is likely to change, a better option would be to use a class or id, if possible.

Andii
  • 337
  • 1
  • 5
  • 19
0

Here are your options with CSS alone using some advanced selectors.

option 1

As there is currently only 1 itemprop div within the #wrapper, just select the div using the itemprop attribute - working fiddle

#wrapper div[itemprop="description"] { // your style }

option 2

This will select the last child element provided it's a div

#wrapper div:last-of-type { // your style }

option 3

As others have pointed out you can use :nth-child() selector. I wouldn't recommend this if the number of divs within #wrapper will vary though.

#wrapper div:nth-child(3) {
  // your style
}

option 4

If you're going to have multiple itemprop divs inside the wrapper you can cancel out styling by selecting siblings. However, this will only work on the itemprop divs within the #wrapper.

#wrapper div[itemprop="description"] { // your style }
#wrapper div[itemprop="description"] ~ div[itemprop="description"] { // cancel out styling }
Jesse
  • 429
  • 6
  • 12