Reputation: 11
I want to get the indexOf the element in an element array in JavaScript.
Here's the code:
function redrawchatbox(chatbox) {
//chatbox is a html element.
chatbox.remove();
variable = variable - 280;
redraw = document.getElementsByName("chatbox");
// this is the error - gives me redraw.indexOf is not a function.
closedchatbox = redraw.indexOf(chatbox);
for (i = redraw.length; i > 0; i--) {
x = i - 1;
redraw[x].style.right = (parseInt(redraw[x].style.right.replace("px", "")) - 280) + "px";
}}
I want to get the index of the chat box closed so I can redraw all the chatbox in the right positions. When I use indexOf on the redraw array it throws me that error.
What can I do to fix this?
Upvotes: 0
Views: 133
Reputation: 144689
That's because getElementsByName
returns a HTMLCollection
which is an array-like object not an array. You should convert the collection into an array then use the indexOf
method.
var chatboxArr = [].slice.call(closedchatbox);
var index = chatboxArr.indexOf(chatbox);
The Array.prototype.slice
method can be used to create a shallow copy of an array. In the above snippet the slice
method is call
ed with the collection as it's this
value and as result it returns an array that contains items of the HTMLCollection
.
Upvotes: 2
Reputation: 353
You get that error because getElementsByName returns a NodeList object.
Upvotes: 0
Reputation: 4081
Replace this:
closedchatbox = redraw.indexOf(chatbox);
with this:
closedchatbox = Array.prototype.indexOf.call(redraw, chatbox);
getElementsByName
returns a NodeList
, which is not an array but an "array-like object". It does not have an indexOf
method itself, but the Array
method can be applied to it in this way.
Upvotes: 0