Reputation: 183
What is the difference between the two?
Say you have
var e = document.getElementById("myelement")
I see an example of something like this:
e.prototype.print = function(){
if(this.nodeType==3)
console.log(this.nodeText);
}
vs an adding new attributes to DOM elements example:
e.accessed = true;
where you're adding the accessed property to element.
It seems like both these examples are adding a new property/attribute to an element, just that the former adds the property to the prototype, so that all objects that inherit the prototype get the new property as well?
So if myelement was the only object inherited from it's prototype, would the following be equivalent to the first example I posted?
e.print=function(){
if(this.nodeType==3)
console.log(this.nodeText);
}
Upvotes: 1
Views: 76
Reputation: 1
Try using document.registerElement
. See Custom Elements , Introduction to Custom Elements
var proto = Object.create(HTMLDivElement.prototype);
proto.print = function() {
console.log(this.nodeName, this.textContent);
return this
}
document.registerElement("x-component", {
extends: "div",
prototype: proto
});
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if ("print" in divs[i]) {
console.log(divs[i].print())
}
}
document.registerElement("x-foo", {
prototype: Object.create(HTMLParagraphElement.prototype, {
print: {
get: function() {
console.log(this.nodeName, this.textContent)
return this;
},
enumerable: true,
configurable: true
}
//,
// specify more members for your prototype.
}),
extends: "p"
});
var foo = document.createElement("p", "x-foo");
foo.innerHTML = 123;
document.body.appendChild(foo);
console.log(foo.print);
<div is="x-component">abc</div>
<div>def</div>
Upvotes: 3