Search code examples
javascriptgetelementsbyname

local copy of document.getElementsByTagName


Why doesn't the following code work?

var f = document.getElementsByTagName;
var x = f('div');

I get "TypeError: Illegal invocation" in Chrome, "TypeError: Type error" in Safari. I don't get an error in Firefox, but it doesn't work. I haven't bothered testing in IE or Opera yet.


Solution

  • In Javascript there is no such thing as a "bound method" (to borrow the term from Python, which I hope you already know or the explanation may need to be longer). When you grab a reference to "document.getElementsByTagName" you are merely getting a reference to a function, not a method associated with the document object. When you call it, "this" is set to the window, not the document, so it doesn't work.

    Technically doing this will get you what you want, but as you can probably see it's pointless:

    var x = f.call(document, 'div')
    

    (It's pointless because it's less readable and not as fast as calling document.getElementsByTagName(). Using a closure is similarly pointless.)