-1

I use this script to find out IDs of elements in a class and then delete them

var ids = [];
var eic = document.getElementsByClassName('classname');
for(var i = 0, length = eic.length; i < length; i++) {
    ids.push(eic[i].id);
    $('#'+eic[i].id).remove(); 
} 

The problem is that when I am trying to delete them, it deletes only some of the elements and the console is returning an error:

"TypeError: eic[i] is undefined"

When I am not trying to delete them, no error is returned and when I alert gained IDs there is every single one.

empiric
  • 7,825
  • 7
  • 37
  • 48
rootz
  • 1
  • 7
  • 1
    Provide the html source - jsfiddle/snippet/codepen/something... – Dekel Sep 19 '16 at 19:04
  • are those elements nested? – ewcz Sep 19 '16 at 19:04
  • 1
    Well if you delete elements then the array gets shorter and you end up looping farther than the array's new length. – JJJ Sep 19 '16 at 19:05
  • Possible duplicate of [Looping through array and removing items, without breaking for loop](http://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop) – JJJ Sep 19 '16 at 19:07
  • 1
    There are easier ways to iterate a nodelist. While a for loop is faster, you can run into out of bounds issues. With ES6 syntax you can get fancy and spread it (`[...document.querySelectorAll(".classname"].forEach/map/etc`) but I suggest you use `eic.forEach` instead. – Sterling Archer Sep 19 '16 at 19:07
  • 1
    Why are you mixing jQuery and DOM? – epascarello Sep 19 '16 at 19:19

1 Answers1

0

Try this one it is working

$(document).ready(function(){

var ids = [];
    $("button").click(function(){
        $(".example").each(function(){
            ids.push(this.id);
            $(this).remove();
        });
        $("#resultArray").text(ids);
      });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Populate array</button>

<div class="example" id="div1">First div element with class="example".</div>

<div class="example" id="div2">Second div element with class="example".</div>

<div class="example" id="div3">Third div element with class="example".</div>

<br>
Array of Ids : <div id="resultArray"><div>
Vijai
  • 2,369
  • 3
  • 25
  • 32