Debsmita Paul
Debsmita Paul

Reputation: 1460

How to select only the first element of a certain class, not it's grand children

I am trying to achieve something like this

<div class="parent">
  <div class="child">
    <div class="item"> <!-- select this -->
      <div class="item"> <!-- not this -->
      </div>
    </div>
  </div>
</div>

I have tried using first-child like this -

.parent .child .item:first-child p {
  background: red;
}
<div class="parent">
  <div class="child">

    <div class="item">  <!-- select this -->
      <p>This should be changed</p>

      <div class="item">  <!-- not this -->
        <p>This should NOT be changed</p>
      </div>

    </div>

  </div>
</div>

But it didn't work. Is there any pure CSS way of doing it?

Upvotes: 0

Views: 56

Answers (3)

Gui Hebling
Gui Hebling

Reputation: 11

You can also use the :first-of-type pseudo-class.

The :first-of-type CSS pseudo-class represents the first element of its type among a group of sibling elements.

Here you're selecting the first div, and then, the first p element.

.parent > .child > .item:first-of-type > p:first-of-type {
  background: red;
}
<div class="parent">
  <div class="child">

    <div class="item">  <!-- select this -->
      <p>This should be changed</p>

      <div class="item">  <!-- not this -->
        <p>This should NOT be changed</p>
      </div>

    </div>

  </div>
</div>

Upvotes: 1

Stefan Bajić
Stefan Bajić

Reputation: 497

You're probably looking for the child combinator:

.parent .child > .item > p {
    background: red;
}
<div class="parent">
    <div class="child">
        <div class="item">  <!-- select this -->
            <p>This should be changed</p>
        <div class="item">  <!-- not this -->
            <p>This should NOT be changed</p>
        </div>
    </div>
</div>

Upvotes: 4

نور
نور

Reputation: 1527

.parent .child .item:first-child > p {
  background: red;
}
<div class="parent">
  <div class="child">

    <div class="item">  <!-- select this -->
      <p>This should be changed</p>

      <div class="item">  <!-- not this -->
        <p>This should NOT be changed</p>
      </div>

    </div>

  </div>
</div>

Upvotes: 1

Related Questions