Home > Software design >  Select first of type element and ignore nested elements
Select first of type element and ignore nested elements

Time:11-21

Please check the link:https://jsfiddle.net/f0hxLru7/

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div >
    <p>hello</p>
    <p>hello</p>
    <div>
      <p>hello</p>
    </div>
  </div>
</body>
</html>
.test p:first-of-type{
  background-color:red
}

I want to change the color of the first p element, in the example I presented first-child would work as I understand but, in the project I am working there are actually more elements, and more could be added, therefore I would like to avoid ever using it. I need to only change the first element of type p in a given div.

CodePudding user response:

Use the child selector > to get only the wanted p element.

See https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator

.test > p:first-of-type{
  background-color:red
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div >
    <p>hello</p>
    <p>hello</p>
    <div>
      <p>hello</p>
    </div>
  </div>
</body>
</html>

CodePudding user response:

The > selector only selects elements that are direct children of the last given element.

So this should do the trick:

.test > p:first-of-type{
  background-color:red
}
  • Related