user2073384
user2073384

Reputation:

NamedItem method with getElementByTagName in Chrome don't work?

I have this code in javascript:

var prop="author";
var optele = theform.getElementsByTagName("input");
alert(optele[prop]);

but in Chrome it returns "undefined" even though I'm sure that the "author" tag exists. Instead, work well in IE and Firefox.

But I noticed that there is a "namedItem" method in optele var in IE and Firefox but there isn't in Chrome.

Someone can help me to run similar code syntax on Chrome?

Upvotes: 1

Views: 2049

Answers (1)

Felix Kling
Felix Kling

Reputation: 816780

That's because IE and FF return a HTMLCollection [MDN] instead of a NodeList [MDN]. NodeList's don't have a way of extracting an element by name or ID (what the namedItem method [MDN] does).

The solution is to not use this feature, but instead iterate over the nodes and compare the name property. Alternatively you could use document.getElementsByName [MDN].

From the MDN getElementsByTagName documentation:

Note: While the W3C specification says elements is a NodeList, this method returns a HTMLCollection both in Gecko and Internet Explorer. Opera returns a NodeList, but with a namedItem method implemented, which makes it similar to a HTMLCollection. As of January 2012, only in WebKit browsers is the returned value a pure NodeList. See bug 14869 for details.

Upvotes: 6

Related Questions