Home > Blockchain >  CSS selector: parent class matches child class
CSS selector: parent class matches child class

Time:09-27

I have a html structure which looks like this:

<ul class = "one">
<li class = "one">one</li>
<li class = "two">two</li>
</ul>



<ul class = "four">
<li class = "three">three</li>
<li class = "four">four</li>
</ul>

I want to create a css selector which selects elements where the parent class and child class match (see also my jsfiddle example. Till now, I'm very explicit about it:

.one > .one,
.two > .two
.three > .three,
.four > .four
{
  color: red
}

Is there a way to be less explicit? Something like: if parent classes match child class?

CodePudding user response:

you cannot select a parent with pure CSS, the pseudo ":has" is just in draft and its not supported by any browser as today. https://developer.mozilla.org/en-US/docs/Web/CSS/:has

It's easy with jquery though

$(function() {
  $("li").each(function(index) {
    if ($(this).parent('ul').attr('class') == $(this).attr('class')) {
      $(this).css('color', 'red')
    }

  });
})

jsfiddle here

  • Related