'How to handle clicks on nested elements? [duplicate]

I am given a task of making 7 nested div's such that the clicked div should change its colour to white, while all the upper div's of clicked div should change their colour to orange. While all the lower div's should change their colour to green.

$(".div").click(function() {
  $(this).css({
    "background-color": "white"
  });
  $(this).parents().css({
    "background-color": "orange"
  });
  $(this).children().css({
    "background-color": "green"
  });
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <title>Document</title>
  <style>
    div {
      border: 2px solid black;
      margin: 30px 20px;
    }
  </style>
</head>

<body>
  <div id="main">
    <div class="div" id="1">
      <div class="div" id="2">
        <div class="div" id="3">
          <div class="div" id="4">
            <div class="div" id="5">
              <div class="div" id="6">
                <div class="div" id="7">
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source