If I add a new property to the prototype of HTMLElement
, and have its default value to be '{}
' (an empty object):
Object.defineProperty(HTMLElement.prototype, 'customObject',
{ configurable: true, enumerable: true, writeable: true, value: {} });
Now I create a new div
(which is also an HTMLElement
):
var e = document.createElement('div');
I assign a property to the customObject
of e
:
e.customObject.prop = "bla";
If I alert it, I see the desired value:
alert(e.customObject.prop); // Displays 'bla'.
Now I create a new, different div
element:
var d = document.createElement('div');
This d
should now have an empty customObject
property, right?
However, if I alert it:
alert (d.customObject.prop);
I get this unexpected result:
bla
How come? When I create a new element shouldn't it have a "blank" instance of HTMLElement.prototype?
( jsfiddle: http://jsfiddle.net/5pgr38mb/ )
EDIT: I am looking for a solution that will work with deep cloning (cloneNode(true)). Meaning - if the custom object has properties on the element or any of its children then that element or child will retain its value in the cloned instance (this is the normal behavior for "native" HTMLElement attributes).
You could override the
document.createElement
function. Just open the console (F12 in most browsers) and click run to see the result of this code.