Possible Duplicate:
Why can’t I have a direct reference to document.createElement?
I am quite new to Js and have been playing around with it.
Since document.getElementById & doucment.createElement is quite long I have decided to put it in a variable;
eg var d = document.createElement;
-
However when I call it like
var someElement = d("p");I get “TypeError: Illegal invocation” and I’m not sure what that means. -
If I separate the
documentobject,var d = document;and then give that a property like so:d.e = d.createElement;then use it to create an elementsomeElement = d.e("p")it works.
Can someone explain what causes 1. to fail and why 2. works?
Thank you in advance.
You need to wrap them in a function so that you can call them from the
documentobject.This is simply a requirement of the
createElementmethod implementation. It needs to know whatdocumentit should be creating the element from.When you detach a method from an object, the method has no memory of the original object.
That’s why this works:
Since
eis a reference to thecreateElementmethod, and it is being called fromd, which is a reference to thedocument, you’re effectively doing the same as: