简体   繁体   中英

Jquery and .parent()

Given the following markup and JS, why does the first statement work and the seond not?

jQuery

$('.selector').change(function () {
  // does work
  $(this).parent(".controls").after( "<div class=\"control-group\">Test</div>" );

  // doesn't work
  $(this).parent(".control-group").after( "<div class=\"control-group\">Test</div>" );
}

HTML

<div class="control-group">
  <label class="control-label" for="description">Section Type</label>
  <div class="controls">
    <select class="selector">
      // options
    </select>
  </div>
</div>

You should use:

  • .closest() , which gives you only the first element matching that selector (starting at the currently selected element), or
  • .parents() to give you all the parents matching that selector (starting at the currently selected element's parent).

The .parent() method only travels a single level up the DOM tree .

BAH! I should have RTFM!

The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM