0

I'm trying to get the index of a span element which I have put in a list. So I create the list with all the elements, but when I'm trying to get the index of an element, by clicking on one of the elements, I've got the error "indexOf is not a function". What can I do to solve this problem and have the expected output ?

var mdr;
window.onload = function() {
  mdr = document.getElementsByClassName("lol");
  for (let i = 0; i < mdr.length; i++) {
    mdr[i].addEventListener("click", haha);
  };
};

function haha() {
  console.log(mdr.indexOf(this));
};
html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

div {
  height: 50px;
  width: 100px;
  background: grey;
  display: flex;
  align-items: center;
  flex-direction: column;
  text-align: center;
}
<div class="lol">1</div>
<div class="lol">2</div>
<div class="lol">3</div>
<div class="lol">4</div>
<div class="lol">5</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Alex
  • 81
  • 1
  • 2
  • 12

1 Answers1

1

The getElementsByClassName() method of Document interface returns an array-like object of all child elements which have all of the given class names.

As the result returned by getElementsByClassName() is not an array indexOf() is not available on the result set.

Try with Spread syntax:

[...mdr].indexOf(this)

OR: With Array.from()

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

Array.from(mdr).indexOf(this)

var mdr;
window.onload = function() {
   mdr = document.getElementsByClassName("lol");
   for (let i = 0; i < mdr.length; i++) {
       mdr[i].addEventListener("click", haha);
   };
};

function haha() {
   console.log(Array.from(mdr).indexOf(this));
};
html, body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
div {
  height: 50px;
  width: 100px;
  background: grey;
  display: flex;
  align-items: center;
  flex-direction: column;
  text-align: center;
}
<div class="lol">1</div>
<div class="lol">2</div>
<div class="lol">3</div>
<div class="lol">4</div>
<div class="lol">5</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59