Question:
In "prototypes" I've used Element.prototype
and HTMLElement.prototype
several times. I would like to know what each one is and what is the difference between them in example, if possible. Because in some tests, like these, I had the same result:
HTMLElement.prototype.tooltip(); // funciona com um elemento normalmente
Element.prototype.tooltip(); // funciona com o mesmo elemento normalmente
Could someone show me the practical difference between the two, if not some concept or specification.
Another question is regarding the NodeList.prototype
, I know so far that I can use it for, for example, the document.querySelectorAll('elemento')
. But I think I would have to use a forEach
and apply an existing prototype
, like this:
HTMLElement.prototype.tooltip = function(){
...
}
NodeList.prototype.tooltip = function(){
[].forEach.call(NodeList, function(el){ // O NodeList dessa Linha, como usá-lo?
el.tooltip() // tooltip já criado para elementos em particulares
})
}
In forEach
I'm trying to use NodeList
as an Array, I could also use Array.from()
, but what I pass as a parameter instead of "NodeList", this
doesn't work…
Thanks in advance.
Answer:
Samir, Element
represents any element in the Document, be it text, html, svg, xml, etc.
The HtmlElement only represents HTML elements, such as a <div>
, <input>
, elements like <svg>
implement the SVGElement
interface.
In this way, HtmlElement
is Base Element
, so any inclusion in Element
's prototype will be reflected in all interfaces that have Element
as base, such as HTMLElement
and SVGelement
.
Note that Element
is based on the Node
interface and NodeList
is a collection of Node
. If you want only HTMLElement
to be affected, then do the following:
NodeList.prototype.forEach = function (callback) {
var indice = 0;
[].forEach.call(this, function (element) {
if (element instanceof HTMLElement) {
callback(element, indice);
indice++;
}
});
};
var blocos = document.querySelectorAll(".bloco");
blocos.forEach(function (element, indice) {
console.log(element, indice);
});
<div class="bloco"></div>
<div class="bloco"></div>
<div class="bloco"></div>
<svg class="bloco"></svg>
<div class="bloco"></div>
Now the same code without Element type checking.
NodeList.prototype.forEach = function (callback) {
[].forEach.call(this, function (element, indice) {
callback(element, indice);
});
};
var blocos = document.querySelectorAll(".bloco");
blocos.forEach(function (element, indice) {
console.log(element, indice);
});
<div class="bloco"></div>
<div class="bloco"></div>
<div class="bloco"></div>
<svg class="bloco"></svg>
<div class="bloco"></div>
If you want the tooltip()
not to be applied over a <svg>
, then use HTMLElement.prototype
, otherwise use Element.prototype