0

In my html code I have 20 input (<input type='text'>)elements. I want to get the index of the element I focused; Hence, before the end of <body>, in <script>, I wrote:

var inputs = document.getElementsByTagName('input');
function getIndex(el){
    console.log(inputs.indexOf(el));
}

and added the following in every input element in html:

<input type='text' onfocus='getIndex(this)'>

but the console says:

Uncaught TypeError: inputs.indexOf is not a function

What am I doing wrong here?

  • 3
    [What do querySelectorAll and getElementsBy* methods return?](https://stackoverflow.com/q/10693845) - your `inputs` is not an array. – VLAZ May 30 '21 at 08:29
  • 1
    Why do you even need the index of the element? You have direct access to the element via `this`, so finding its index seems superfluous. – VLAZ May 30 '21 at 08:30
  • I would get the index of the input element and there is a `
    ` associated with every input whose property I want to change say : `document.querySelectorAll('.parentDiv div')[index].style.color='blue';`
    – Satyam Mishra May 30 '21 at 08:41
  • And you expect those indexes to match? Seems better to have a more robust system where you nest the tags. Then you can just traverse the DOM to find them, instead of having to look them up by index. – VLAZ May 30 '21 at 08:47

3 Answers3

3

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name

You can make the collection into array using either Array.from() or Spread syntax (...)

var inputs = document.getElementsByTagName('input');
function getIndex(el){
    console.log([...inputs].indexOf(el));
}
<input type='text' onfocus='getIndex(this)'>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

As described here and here, you can use Array.prototype.indexOf.call to apply the Array indexOf() function on the NodeList.

const inputs = document.getElementsByTagName('input');
function getIndex(el) {
  console.log(Array.prototype.indexOf.call(inputs, el));
}
<input type='text' onfocus='getIndex(this)'>
loop
  • 825
  • 6
  • 15
0

Good question! This is a little tricky!

This happens because .indexOf runs on an Array and document.getElementsByTagName returns a HTMLCollection, which is not an array.

You can simple convert it into an array and then use it: var arr = [...htmlCollection]; or var arr = [].slice.call(htmlCollection);

See this answer for more details!