Search code examples
javascriptwordpressjquery-selectors

Selecting parents slements in DOM in Wordpress


I have DIV wrapper which I want to toogle class using children element. However the DOM three isn't the best:

<div class="wrapper-I-want-to-toogle-class">
   <div class="other-class">
      <div class="other-class">
         <span class="element-I-want-to-triggle-toogle-class">X</span>
      </div>
   </div>
</div>

How to do that? I have alredy tried to use:

$(this).parents(".wrapper").classList.toogle('active');

However wordpress does not really allow to use functions like that. Can You help me?


Solution

  • Something like this should work, its important to select the correct class name of the parent, and the child used to toggle the parent

    jQuery(function(){
      jQuery('.target').click(function(){
        jQuery(this).parents(".wrapper").toggleClass('active');
      })
    })
    .wrapper{
      display:block;
      height:20px;
      background:#CCC;
    }
    .wrapper.active{
      height:150px;
    }
    .target {
     float:right;
     display:flex;
     background:#EEE;
     color:#666;
     border:1px solid #aaa;
     width:20px;
     height:20px;
     justify-content:center;
     align-content:middel;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="wrapper">
       <div class="other-class">
          <div class="other-class">
             <span class="target">X</span>
          </div>
       </div>
    </div>