Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector for immediately succeeding child element

Tags:

jquery

css

Two simple HTML examples:

<p>
  <i>Some text</i>
</p>

<p>Here's a paragraph that has <i>some text</i>, and then some more</p>

When using CSS, this selects the <i>'s in both cases:

p > i {
  border: 1px solid red;
}

> targets every <i> within every <p>.

What I'm looking for is a way to only target the <i>'s that immediately follow upon the <p>, in other words, that targets the <i> in the first example but not in the second. Kind of in a way that + selects adjacent siblings, but for adjacent children. Is this possible?

I looked into jQuery's only-child selector, but this also targets the <i>'s in both examples, since the text ("here's a paragraph...") isn't considered a child.

like image 813
Ack Avatar asked Mar 16 '26 02:03

Ack


1 Answers

You can't do this work using CSS but using javascript/jquery you can select target element as shown in bottom.

Select all i element and use .filter() to filtering selected elements. In filter callback check previous text of i using previousSibling property.

$("p > i").filter(function(){
  return this.previousSibling.nodeValue.trim() == "";
}).css("border", "1px solid red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <i>Some text</i>
</p>
<p>Here's a paragraph that has <i>some text</i>, and then some more</p>
<p>
  <i>Some text</i>
</p>
<p>text <i>some text</i>, text</p>
like image 167
Mohammad Avatar answered Mar 17 '26 15:03

Mohammad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!