title: Hooking document.createElement using function prototype
body: <p>I want to hook onto the document.createElement function in such a way that, every time I create a div element, my hook will attach a "foo" attribute to the div. This is what I have currently:</p>
  
  <pre><code>&lt;script&gt;
      window.onload = function () {
          console.log("document loaded");
          document.prototype.createElement = function (input) {
              var div = document.createElement(input);
              console.log("createElement hook attached!");
              if (input == "div")div.foo = "bar";
              return div;
          }
  
          document.body.addEventListener('onready', function () {
              var div = document.createElement("div");
              console.log(div.foo);
          });
  
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>When I run this in Chrome, I get an error saying</p>
  
  <pre><code>Uncaught TypeError: Cannot set property 'createElement' of undefined test.html:4 window.onload
  </code></pre>
  
  <p>(I changed the line number in the error message above to match my code)</p>
  
  <p>What am I wrong here? How can I fix this?</p>