Components of Class
Learn about the components of classes in JavaScript.
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:
Press + to interact
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 ...