0

I have multiple input fields assigned to a particular classname. Now I want to fetch the index of the classname of the input field and console.log() it.

This is my code:

document.querySelectorAll('.class-name').forEach(item => {
    item.addEventListener('change', event => {
        console.log(item); //print the index of the item
    })
})

How can I do that? Please help me.

4 Answers4

0

The forEach() function allows to define an index variable in order to track each item index. Since the index variable mantains its context when call it from the eventListener, you can use it to get the index number:

document.querySelectorAll('.class-name').forEach((item, index) => {   // Here define the index variable
    item.addEventListener('click', event => {
        console.log(index); //print the index of the item
    })
})
<button class="class-name">Click index 0</button>
<button class="class-name">Click index 1</button>
<button class="class-name">Click index 2</button>
AlexSp3
  • 2,201
  • 2
  • 7
  • 24
0

The forEach() loop takes 2 arguments, the second being optional, and the index. So you could do it like this:

document.querySelectorAll('.class-name').forEach((item, index) => {
    item.addEventListener('change', event => {
        console.log(index); //print the index of the item
    })
});

More about the forEach() loop here.

Martin
  • 2,326
  • 1
  • 12
  • 22
0

try to pass the index for each

document.querySelectorAll('.class-name').forEach((item, index) => {
    item.addEventListener('change', event => {
        console.log(item, index); //print the index of the item
    })
})
0

May be like this?

document.querySelectorAll('.class-name').forEach((item, index) => {
    item.addEventListener('change', event => {
        console.log(index); //print the index of the item
    })
})
nosdmitry
  • 5
  • 2