Reputation: 177885
Apologies if this is a duplicate - it is not easy to search for.
I have today come across TWO questions using someArrayOrCollection.item(i)
instead of my preferred someArrayOrCollection[i]
Example: parse XML attribute value using javascript
var sTitle1 = item.getElementsByTagName("title").item(0)....
where I would use
var sTitle1 = item.getElementsByTagName("title")[0]....
Last time I saw these where when only IE supported that notation.
My first instinct when I see .item() is to correct it to []. Should I or is it harmless or perhaps even best practice these days?
Interestingly almost all the collections at MDN mentions the item method but their examples use [] - for example https://developer.mozilla.org/en-US/docs/Web/API/NodeList
Upvotes: 2
Views: 637
Reputation: 214959
For NamedNodeMap
s []
acts as a sugar for both .item
and .getNamedItem
, which makes it possible to build a contrived example where index will be different from .item
:
<div id="x" 2e0="wtf" class="foo" ></div>
<script>
a = document.getElementById("x").attributes;
console.log(a["2e0"].nodeValue) // wtf
console.log(a.item("2e0").nodeValue) // foo
</script>
Needless to say, this is purely theoretical, in the real life []
is a safe choice.
Upvotes: 4