Reputation: 80
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?
Upvotes: 0
Views: 2477
Reputation: 39
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!
Upvotes: 0
Reputation: 963
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)'>
Upvotes: 0
Reputation: 68933
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)'>
Upvotes: 3