开发者

Array.prototype function not working for document.forms[0].elements

I have built a prototype function for Arrays and it doesn't allow me to use it with an array from document.forms[0].elements. Here is a simplified script that shows this problem

<html>
<body>

<form id="frm1" action="form_action.asp">
  First name: <input type="text" name="fname" value="Donald" /><br />
  Last name: <i开发者_运维问答nput type="text" name="lname" value="Duck" /><br />
  <input type="submit" value="Submit" />
</form> 


<p>Return the value of each element in the form:</p>
<script type="text/javascript">
Array.prototype.returnFirst = function(){
   return this[0];
}
alert([1,2,3].returnFirst()); //Why does this work?
alert(document.forms[0].elements.returnFirst().id); //but this one doesn't?
</script>

</body>
</html>

You will see with this that the returnFirst() prototype function works for my [1,2,3] array but not for my array of elements? Why is this, it is still an array?


That's not a real array, so it doesn't inherit Array.prototype.

It's actually an HTMLCollection, as you can discover by calling toString() on it.

If you want to, you can modify HTMLCollection.prototype, but modifying DOM prototypes is discouraged.

EDIT:

You can turn it into a real array by calling

var arr = Array.prototype.slice.call(document.forms[0].elements);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜