DEV Community


Discussion on: DOM elements with ID's are global variables

russellbeattie profile image
Russell Beattie

As someone who's been doing web development from the beginning of browsers, this isn't a surprise, as that's how it was done, and HTML is very backwards compatible. But what I didn't know (because I've long since stopped using this 'feature') is how Chrome treats elements with the same ID! Wow, that's weird. I just checked, and it returns an HTMLCollection, which is array-like, but not actually an array. And according to the MDN docs, Opera (I assume the old one) returns a NodeList.

I guess the different implementations is a good thing - if browser engines all acted the same, developers would end up using this old method regularly, but as it is, the best way to be cross-browser is by using an explicit getElementById instead.