如何在jQuery中对最近的div使用最近的()

I'd like to remove the closest error-class. If I select a_1 it should remove the span after it. Same for a_2. But in div .b it should remove the error-class no matter which input I select. How can I achive this?

// doesn't work
form.each(function() {
    $(this).closest('.error').remove();
});
<div class="a">
  <input class="a_1" type="text"> <!-- if I'm here, remove next -->
  <span class="error">Error</span>
  <input class="a_2" type="text"> <!-- if I'm here, remove next -->
  <span class="error">Error</span>
</div>

<div class="b">
  <input class="b_1" type="text">
  <input class="b_2" type="text">
  <input class="b_3" type="text">
  <input class="b_4" type="text">
  <input class="b_5" type="text">
  <span class="error">Error</span> <!-- remove this -->
</div>
评论
  • hquae
    hquae 回复

    You can use .nextAll() method instead to get the next sibling elements with class error and then use :first selector to get the first element only, so that we can only remove it where there is an actual error.

    演示:

    var $form = $(':input');
    $form.each(function(){
      $(this).nextAll('.error:first').remove();
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="a">
      <input class="a_1" type="text"> <!-- if I'm here, remove next -->
      <span class="error">Error</span>
      <input class="a_2" type="text"> <!-- if I'm here, remove next -->
      <span class="error">Error</span>
    </div>
    
    <div class="b">
      <input class="b_1" type="text">
      <input class="b_2" type="text">
      <input class="b_3" type="text">
      <input class="b_4" type="text">
      <input class="b_5" type="text">
      <span class="error">Error</span> <!-- remove this -->
    </div>