How to use closest() in jQuery for specific div

Viewed 42

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>

2 Answers

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.

Demo:

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>

To validate inputs are empty or not and to see if the code is really working:

Demo:

var $form = $(':input');
$form.each(function() {
  // if the input is not empty, hide error 
  if ($(this).val().trim() !== '') {
    $(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" value="some text here"> <!-- 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>

Related