Search code examples
jquerycssparentaddclass

jQuery add class to parent if condition is true in child


Is there a way I can use jQuery to add a class to the parent element if the child element meets a certain condition?

I want this code:

<ul>
  <li>
     <a href="first.html">First</a>
  </li>
  <li>
     <a class="flyout-toggle" href="second.html">Second</a>
  </li>
</ul>

To change to this:

<ul>
  <li>
     <a href="first.html">First</a>
  </li>
  <li class="has-flyout">
     <a class="flyout-toggle" href="second.html">Second</a>
  </li>
</ul>

Solution

  • $('a.flyout-toggle').parent().addClass('has-flyout');