1

here I have to change after background-color on hover sub menu li first child only for the first child I want to change bg color. I had tried using selector ~ but still not working can anyone suggest me in the right direction.

.main {
 position: relative;
}
.main:after {
 content: 'After';
 position: absolute;
 top: -10px;
 width: 50px;
 height: 15px;
 background-color: red;
}
.demo:first-child:hover .main:after { background-color: blue;}
<ul class="main">
 <li>
  test
  <ul class="demo">
   <li><a>change bg after</a></li>
   <li><a>test2</a></li>
  </ul>
 </li>
 <li>test</li>
 <li>test</li>
 <li>test</li>
</ul>
Husna
  • 1,152
  • 2
  • 13
  • 32

2 Answers2

2

We can't select parent using CSS, so I used jquery for you please check below code:

$(document).ready(function(){
  $(document).on({
      mouseenter: function() {
          $(".main").addClass("hovered");
      },
      mouseleave: function() {
          $(".main").removeClass("hovered");
      }
  }, ".main li:first-child ul > li:first-child");
});
.main {
 position: relative;
}
.main:after {
 content: 'After';
 position: absolute;
 top: -10px;
 width: 50px;
 height: 15px;
 background-color: red;
}
.main.hovered:after { background-color: blue;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="main">
 <li>
  test
  <ul class="demo">
   <li><a>change bg after</a></li>
   <li><a>test2</a></li>
  </ul>
 </li>
 <li>test</li>
 <li>test</li>
 <li>test</li>
</ul>
Shivasagar
  • 177
  • 2
1

document.querySelector('ul.demo li:first-child').addEventListener('mouseover', () => document.querySelector('ul.main').classList.add('hover'));
document.querySelector('ul.demo li:first-child').addEventListener('mouseout', () => document.querySelector('ul.main').classList.remove('hover'));
.main {
  position: relative;
}

.main:after {
  content: 'After';
  position: absolute;
  top: -10px;
  width: 50px;
  height: 15px;
  background-color: red;
}

.main.hover:after {
  background-color: blue;
}
<ul class="main">
  <li>
    test
    <ul class="demo">
      <li><a>change bg after</a></li>
      <li><a>test2</a></li>
    </ul>
  </li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
Umair Khan
  • 1,343
  • 13
  • 27