Search⌘ K
AI Features

Components of Class

Explore how to build reusable HTML components using JavaScript classes. Understand constructors, methods like render(), and how to apply inheritance with extends and super keywords to create specialized components such as Warning, Success, and Info notices. Gain practical skills to manage class properties and styles for dynamic web content.

We'll cover the following...

Classy components

One use of classes is to create reusable HTML components. This allows you to define a block of HTML in a single class and then reuse it multiple times in a program.

For example, let’s create a class called Notice and use it to create a <div> element that displays a message on a web page. Enter the following code in the index.js file:

Javascript (babel-node)
class Notice {
constructor(message = 'Hello, World!') {
this.element = document.createElement('div');
this.element.textContent = message;
this.css = 'background:silver;border:3px gray solid;color:gray;font:18px sans-serif;padding:8px;margin:10px';
this.element.style.cssText = this.css;
}
render(element) {
element.appendChild(this.element);
}
}

The constructor function of this class creates a <div> element and then sets the textContent property to be the same as message, which is provided as an argument when creating a new instance. It also sets the CSS properties using the style.cssText property, which allows us to set multiple CSS ...