Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
  </head>
  <body>
    <div class="container-1">
      <div class="container-2">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
        <div class="box"></div>
      </div>
    </div>
    
    <button>Apply background effect to all ancestors of the black box</button>
  </body>
</html>
 
.container-1 {
  display: flex;
  width: 300px;
  height: 300px;
  border: 1px solid black;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px
}
.container-2 {
  display: flex;
  width: 200px;
  height: 200px;
  justify-content: center;
  align-items: center;
  border: 1px solid black;
}
.box {
  width: 100px;
  height: 100px;
  border: 3px solid white;
  background-color: black
}
.backgroundEffect {
  background-color: red;
}
 
$(() => {
  $('button').click(() => {
    // this will apply the class to "all" ancestors
    $('.box').parents().toggleClass('backgroundEffect')
    
    /* 
    uncomment the line below and observe the difference; 
    we are using method chaining here to target 
    only the "grandparent" of the black box 
    */
    
    //$('.box').parent().parent().toggleClass('backgroundEffect')
  })
})
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x