jemz
jemz

Reputation: 5143

Jquery deleting element given by index

I have this div.form-group dynamically added. I have button to click to get the index. my problem is that when I delete an elment using index the third div also is deleted. how can I delete only one div by the given index, if I delete again looks like it's not updating index after it remove. is this because it is dynamically added ?

<div class="mycontainer">
      <div class="form-group">
         <input type="text" class="form-control">
      </div>
                                                        
       <div class="form-group">
           <input type="text" class="form-control">
       </div>

       <div class="form-group">
         <input type="text" class="form-control" >
       </div>

       <div class="form-group">
         <input type="text" class="form-control" >
       </div>

    </div>



$('.mycontainer').find('div.form-group').eq(index).remove();

Upvotes: 0

Views: 284

Answers (2)

user15295674
user15295674

Reputation:

Your code working fine... check isn't your script runs twice.

$('.mycontainer').find('div.form-group').eq(1).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="mycontainer">
      <div class="form-group">
         <input type="text" value="0" class="form-control">
      </div>
                                                        
       <div class="form-group">
           <input type="text" value="1" class="form-control">
       </div>

       <div class="form-group">
         <input type="text" value="2" class="form-control" >
       </div>

       <div class="form-group">
         <input type="text" value="3" class="form-control" >
       </div>
</div>

Upvotes: 1

KooiInc
KooiInc

Reputation: 122966

Actually, you really don't need jQuery for it:

const removeByIndex = (index = 0) => 
  [...document.querySelectorAll('.mycontainer .form-group')][index].remove();

setTimeout(() => removeByIndex(2), 2000);
<div class="mycontainer">
  <div class="form-group">
    <input type="text" class="form-control">
  </div>

  <div class="form-group">
    <input type="text" class="form-control">
  </div>

  <div class="form-group">
    <input type="text" class="form-control" value="will be removed ...">
  </div>

  <div class="form-group">
    <input type="text" class="form-control">
  </div>

</div>

Upvotes: 1

Related Questions