E
E
Evgeniy Liferov2015-10-16 15:59:31
css
Evgeniy Liferov, 2015-10-16 15:59:31

How to change color of parent div when hovering over child?

There is a menu with nested items. When you hover over the selected item, "it" drops out and becomes #F5F5F5 in color, but when the cursor moves over the dropped sections, the selected item should have the color #F5F5F5.
Here is the HTML code.

<ul id="nav"> 
  <li>
            <a class="MenuBlock_1" href="#">Родитель</a>
    <ul class="MenuBlock_1_panel">
      <li><a href="#">Первый пункт</a></li>
      <li><a href="#">Второй</a></li>
      <li><a href="#">Третий</a></li>
    </ul>
    </div>
  </li>

I wanted to do this:
#nav ul.MenuBlock_1_panel:hover + li .MenuBlock_1{
  background:#F5F5F5;
}

But then I found out that you cannot change the style of the parent element in CSS. I was looking for how to do it in JavaScript, I found a couple of options, but there was a problem how to specify with "li ul" tags.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Valery, 2015-10-16
@batareika

Your menu drops out when you hover over #nav li, right?
When #nav li:hoverthis item changes color and the menu that is in this li?
The problem should be simple
#nav li:hover > a { background: #f5f5f5; }

D
Denis, 2015-10-16
@Deonisius

there was a problem how to specify with "li ul" tags
This moment I did not quite understand something; specify. But maybe this option will work without clarification:
[].forEach.call(document.querySelectorAll('.MenuBlock_1_panel'), function (el) {
    el.addEventListener('mouseenter', function () {
        this.previousElementSibling.style.backgroundColor = '#F5F5F5';
    }, false);
    el.addEventListener('mouseleave', function () {
        this.previousElementSibling.style.backgroundColor = '';
    }, false);
});

S
sashabeep, 2015-10-17
@sashabeep

And what prevents you from switching the class of the parent on hover?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question