Chun Wai
Chun Wai

Reputation: 33

Javascript get index value using this variable

When I click li links, I would like to get index value using this variable. How I can achieve it?

let liList = document.getElementsByTagName("li");
for (let i = 0; i < liList.length; i++) {
    liList[i].onclick = function () {
       alert(liList.indexOf.call(this));        //I want to use this to get i value
    };
 }
<ul>
    <li>11</li>
    <li>22</li>
    <li>33</li>
</ul>

Upvotes: 2

Views: 281

Answers (2)

jeprubio
jeprubio

Reputation: 18002

If you want to get the index of the clicked value there is no need to do the indexOf, you have the index in your loops i var:

let liList = document.getElementsByTagName("li");
for (let i = 0; i < liList.length; i++) {
    liList[i].onclick = function () {
       console.log(i);
    };
 }
<ul>
    <li>11</li>
    <li>22</li>
    <li>33</li>
</ul>

And if you really want to do indexOf() you should transform that HTMLCollection returned from getElementsByTagName() to an array first:

let liList = document.getElementsByTagName("li");
for (let i = 0; i < liList.length; i++) {
    liList[i].onclick = function () {
        let arr = Array.prototype.slice.call( liList, 0 ); // transform in array
        console.log(arr.indexOf(this));
    };
 }
<ul>
    <li>11</li>
    <li>22</li>
    <li>33</li>
</ul>

Upvotes: 2

Jesper Martinez
Jesper Martinez

Reputation: 631

This will fix your problem. Thanks

    let liList = document.getElementsByTagName("li");
    for (let i = 0; i < liList.length; i++) {
        liList[i].onclick = function () {
           console.log(liList[i].innerHTML);  /* li value that you want to get or */  
           console.log(i); /* Index value that you want to get */
        };
    }
<ul>
  <li>11</li>
  <li>22</li>
  <li>33</li>
</ul>

Upvotes: 0

Related Questions