Languages
[Edit]
EN

HTML - Element, Text, Comment, Node, etc. inheritance

7 points
Created by:
Rogan-Wilkes
727

In this article, we would like to show you HTML elements inheritance concept.

Every HTML element is a Node (it means HTMLElement extends Element that extends Node, etc.). As you can see, Text and Comment are located on different branches and they are also Nodes. Elements like: <div>, <p>, <img>, <br>, <body>, etc. are HTMLElements.

Overview:

How HTML elements extends / inherits from others (from Node).
How HTML elements extends / inherits from others (from Node).

Practical examples

In this section, we create instances of Text, Element, and Comment HTML elements and use instanceof operator to present the elements inheritance.

Text

Text is a node that presents text on a website. Text nodes are located in HTML elements.

// ONLINE-RUNNER:browser;

// create text node
const textNode = document.createTextNode('text');


// check if the node is instance of Text, Node, etc.

console.log(textNode instanceof Text);			// true
console.log(textNode instanceof Node);			// true
console.log(textNode instanceof EventTarget);	// true

console.log(textNode instanceof Comment);		// false
console.log(textNode instanceof Element);		// false
console.log(textNode instanceof HTMLElement);	// false

HTMLElement

HTML elements build website layout. In the below example we used <div> as an example element.

// ONLINE-RUNNER:browser;

// create element
const element = document.createElement('div');


// check if the element is instance of Element, Node, etc.

console.log(element instanceof HTMLElement);	// true
console.log(element instanceof Element);		// true
console.log(element instanceof Node);			// true
console.log(element instanceof EventTarget);	// true

console.log(element instanceof Text);			// false
console.log(element instanceof Comment);		// false

Comment

Comments are useful to mark some important things in the source core. The user doesn't see them by default.

// ONLINE-RUNNER:browser;

// create comment
const comment = document.createComment('comment')


// check if the comment is instance of Comment, Node, etc.

console.log(comment instanceof Comment);		// true
console.log(comment instanceof Node);			// true
console.log(comment instanceof EventTarget);	// true

console.log(comment instanceof Text);			// false
console.log(comment instanceof Element);		// false
console.log(comment instanceof HTMLElement);	// false

References

  1. instanceof - JavaScript | MDN 

Alternative titles

  1. HTML - Node types and its inheritance model
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join