Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Element.prototype undefined?

Tags:

javascript

Surprisingly, this Apple page has Element.prototype equal to undefined, so I cannot use this awesome snippet of code.

Are there any reason for doing this?

like image 800
Randomblue Avatar asked Nov 25 '11 12:11

Randomblue


2 Answers

Apple is using the Coherent JS framework which has this block of code:

//  Trick picked up from Prototype to get around IE8's fixed Element & Event
(function() {
  var element = this.Element;
  this.Element = {};
  Object.extend(this.Element, element || {});
}).call(window);

window.Element is originally a function, but it's being replaced and extended with a regular object. Only functions have .prototype properties.

Workaround:

The prototype chain for any HTML element seems to be:

  • Specific element type (HTMLBodyElement, HTMLDivElement, etc...)
  • HTMLElement
  • Element
  • Node
  • Object

You should be able to attach your referenced code to the prototype to any of the bold objects in the chain and get the style for an html element. I would not recommend this in production code as modifying objects like that is generally considered harmful, but if you are just trying to export a style from another website, it should work well enough.

Object.prototype.exportStyles = (function () {   //Works if you use it on an element, the code will protect you from yourself if you try to use it on regular objects.
HTMLElement.prototype.exportStyles = (function () {   //Safer because it is farther down the inheritance line, affecting fewer objects.
                                                      //Avoiding name collisions and other surprises.
like image 109
Dennis Avatar answered Nov 05 '22 00:11

Dennis


In addition to what Dennis explained well, the easiest solution to avoid changing built-in objects (which people seem to love to do over and over, as Apple did on their site and Luc1245 did in the post you've mentioned).

A non-intrusive alternative is to run something like:

function exportStyles = ( function ( /* what Luc1245 posted */;

exportStyles.apply( /* this */ theElement, /* args */ []);
like image 20
Kos Avatar answered Nov 04 '22 23:11

Kos