2

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>

5
  • liList.indexOf(this) ? Though the i is let scoped, so not sure why you couldn't just use it. Or use a forEach with a closure to get the index and not need this logic. Commented May 6, 2020 at 13:47
  • 1
    what do you mean by index value? Commented May 6, 2020 at 13:59
  • liList.indexOf(this) , this is only example I actually cannot find any method to get it. I know alert(i) I can get index (e.g. I click 11, it return 0). Since I learn to simulate jquery index() method, I want to use this to get index Commented May 6, 2020 at 14:13
  • Did you try my answer below sir? Please let me know. Thanks Commented May 6, 2020 at 14:15
  • Yes. I try. But I want not to use i variable, is it possible use "this" to get i value Commented May 6, 2020 at 14:22

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

yes, this is really I want, but i also thank all quick reply and help
I'm glad I could help.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.