kampageddon kampageddon - 10 days ago 5
CSS Question

CSS multiple parent selector

I would change the CSS rule for the background to li.li-class if it contain an h3.
I have an HTML like this:

<div class="div-class">
<ul>
<li class="li-class">
<span itemprop="something">
<h3>Some title</h3>
</span>
</li>
</ul>
</div>


and the CSS for li background is:

.div-class ul li:nth-child(2n+1) { background: #f4f4f4; }


Where is the CSS selector for the li.li-class?

I have look this question Is there a CSS parent selector? and i try the code, but not work in this case.
Thanks all

Answer

As mentioned in comments, this is not possible using pure CSS.

It would however be very straight forward using the jQuery .has():

$("li").has("h3").addClass("yellow");

For the HTML:

<style>
.yellow{
  background-color:yellow;
}
</style>    
<div class="div-class">
  <ul>
    <li class="li-class">
      <span itemprop="something">
        <h3>Some title</h3>
      </span>
    </li>
    <li class="li-class">
      <span itemprop="something">
        <p>
          Not a header
        </p>
      </span>
    </li>
  </ul>
</div>

Will look at every li element and if it has a descendant h3 element it will add the yellow class to the li.

JSFiddle example

You can also make the selector more specific, so it does not select all lis but only the ones in a <div class="div-class"> with something like

$("div.div-class").find("li").has("h3").addClass("yellow");
Comments