Search code examples
jquerygravity-forms-plugin

Limiting the scope of jquery script to immediate ancestors


I've written this script to find <fieldset> tags with a child containing gfield_error, and add a class wow-error into that <fieldset>.

The problem is it works too well and if it finds gfield_error anywhere on the page it adds the class to every <fieldset> on the page, not just those with a child that has gfield_error.

jQuery(document).ready(function( $ ) {
$(':has(.gfield_error) > fieldset').addClass('wow-error');
});

<fieldset class="gfieldset">
    <legend class="gfieldset-legend ">Name</legend>
    <ul class="gform_fields">
        <li id="field_2_95" class="gfield gfield_error">
                <p>Some content</p>
        </li>
    </ul>
</fieldset>

I'm sure it's an elementary mistake, could anyone offer guidance.


Solution

  • My first thought is to turn it around — find any .gfield_error then get the gfieldset it is within, using .closest()

    $('#demo').on('click', function() {
        $('.gfield_error')
            .closest('fieldset.gfieldset')
            .addClass('wow-error');
    });
    fieldset {
      margin: 1em;
      border: 1px solid gray;
    }
    .wow-error {
      background-color: lightyellow;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <fieldset class="gfieldset">
      <legend class="gfieldset-legend">Name</legend>
      <ul class="gform_fields">
        <li id="field_2_95" class="gfield gfield_error">
          <p>Some content in matching fieldset</p>
        </li>
      </ul>
    </fieldset>
    
    <fieldset class="not-gfieldset">
      <legend class="gfieldset-legend">Name</legend>
      <ul class="gform_fields">
        <li id="field_2_96" class="gfield gfield_error">
          <p>Some content in non-matching fieldset<br>
             This is a fieldset but it's not a .gfieldset, so even though
             if contains a .gfield_error it does not get selected.</p>
        </li>
      </ul>
    </fieldset>
    
    <fieldset class="gfieldset">
      <legend class="gfieldset-legend">Name</legend>
      <ul class="gform_fields">
        <li id="field_2_97" class="gfield not-gfield_error">
          <p>Some content in matching fieldset w/o gfield_error.<br>
             This is a .gfieldset but it does not contain a .gfield_error</p>
        </li>
      </ul>
    </fieldset>
    
    <fieldset class="gfieldset">
      <legend class="gfieldset-legend">Name</legend>
      <ul class="gform_fields">
        <li id="field_2_98" class="gfield gfield_error">
          <p>Another matching fieldset</p>
        </li>
      </ul>
    </fieldset>
    
    <button type="button" id="demo">Demonstrate</button>