Home > database >  Why can the same methods as HTMLElement be applied to an instance of Element?
Why can the same methods as HTMLElement be applied to an instance of Element?

Time:08-10

HTMLElement inherits properties/methods from the Element interface. But, why on an instance of Element, it works even when I use the same properties and methods which are defined on HTMLElement. For example, in the given code, querySelector gives back Element which doesn't have a style property defined on it (HTMLElement does). But, it works when I apply the style property on it. Also, instanceof HTMLElement gives back true. It should only be instanceof Event, Node, and Element that gives back true since Element inherits from all three. I know HTMLElement can inherit methods/properties from Element but is it also vice-versa? MDN Docs DOM Interfaces

var somefield = document.querySelector('#lname');
somefield.style.background = 'yellow'
somefield instanceof HTMLElement; //True

CodePudding user response:

querySelector will

return the first Element within the document that matches the specified selector, or group of selectors

An element can also be an HTMLElement. If element in the document happens to be an HTMLElement, then you will be able to use methods on HTMLElements on the result.

But the element isn't necessarily an HTMLElement. For example, if you happen to be working with an XML document, you won't get an HTMLElement in return, and won't be able to use HTMLElement methods:

const xmlStr = '<q id="a"><span id="b">hey!</span></q>';
const doc = new DOMParser().parseFromString(xmlStr, "application/xml");
const b = doc.documentElement.querySelector('#b');
console.log(b instanceof Element); // true
console.log(b instanceof HTMLElement); // false

// error:
b.style.background = 'yellow';

querySelector, if it finds anything at all, is guaranteed to return at least an Element, but it will often return a more specific type - not only an HTMLElement, but often something even more specific, like an HTMLInputElement - on which HTMLInputElement-specific methods and properties can be used.

CodePudding user response:

There are no elements on a page that are just Element instances. The interface serves as a parent "class" so HTMLElement, SVGElement and XULElement (and others) can inherit methods common to all elements.

  • Related