How to style nested div when mouseover its parent div

Hi! I’m trying to solve this problem:

Whenever you mouseover any div class =“square-container”, and that specific div you just mouseovered contains a div class =“bottom-line”, that nested div class =“bottom-line” should be restyled.

What would you do?

Here’s my JavaScript attempt, the HTML and the CSS. It works, but only when there’s one div class =“square-container”.

const squareContainer = document.querySelector('.square-container');
const bottomLine = document.querySelector('.bottom-line');

function fullLength() {
    bottomLine.style.width = '100%';
}
    
function noLength() {
    bottomLine.style.width = '0';
}

squareContainer.addEventListener('mouseenter', fullLength);
squareContainer.addEventListener('mouseleave', noLength);

Here’s the html

<div class="container">
        
        <div class="square-container" id="squareContainer">
            <div class="red-square">
                This is red
            </div>
            
            <div id="bottomLine" class="bottom-line"></div>
        </div>

        <div class="square-container" id="squareContainer">
            <div class="red-square">
                This is red
            </div>
            
            <div id="bottomLine" class="bottom-line"></div>
        </div>

        <div class="square-container" id="squareContainer">
            <div class="red-square">
                This is red
            </div>
            
            <div id="bottomLine" class="bottom-line"></div>
        </div>
        
    </div>

Here’s the css

/* CSS reset */

*,
::after,*::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
html {
  height: 100%;
}

.container {
  border: 1px solid black;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.square-container {
  border: 1px solid blue;
  border-radius: 5px;
  margin: 1em;
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  padding: 15px;

}

.red-square {
  width: 5em;
  height: 5em;
  background-color: red;
  margin-bottom: 5px;
  text-align: center;
}

.bottom-line {
  width: 50%;
  height: 5px;
  transition: 0.3s;
  position: absolute;
  bottom: 0;
  left: 0;
  background-color: black;
}
  • Grab all the square-container elements using document.querySelectorAll

  • Loop them and add the event listeners.

  • Inside each handler get the target and loop the children, look at the class name(s) using for example classList and contains.

  • Add or remove the styles based on the class names. I would suggest using a class for the styles and using classList.

Example:

Could you also do this with CSS?

.square-container:hover .bottom-line {
  /* styles */
}
1 Like