Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
html
community creator

How to create your own HTML element

Josias Aurel

Have you ever thought about creating your own HTML element? If you’ve used a frontend framework like React, Vue, or Angular, you might have been amazed that you can create any component and reuse it throughout your app. What will typically happen with your elements is that they get compiled down into some Javascript, which takes care of the DOM.

But what about actually creating an HTML element? That is what we are going to learn in this post. At the end of this tutorial, you will be able to create your own basic HTML element.

To get started, create a new folder to contain the code from this tutorial. Open that folder and create three files named index.html, style.css and main.js.

We are going to start with the usual HTML boilerplate like below :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Custom Element</title>
</head>
<body>
    <script src="main.js"></script>
</body>
</html>

Now that we have our basic HTML code, let’s get a name for our element. I will name it hello-world, a pretty simple name ;).

Now, add your element into the HTML code, between the body tags above the script tag. You can add any text between your element tags. Your final HTML should look like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Custom Element</title>
</head>
<body>
    <hello-world id="hello" ishidden>
        Hello World
    </hello-world>
    <script src="main.js"></script>
</body>
</html>

We are done with the HTML code; now, it’s time to write some Javascript. Create a class named HelloWorld that extends HTMLElement.

// Creating my own custom HTML element

class HelloWorld extends HTMLElement {

}

Now, we need to define our element to make the browser aware that we are creating a new element that will be reused. After the class, add the following line of code:

customElements.define("hello-world", HelloWorld)

What is this? The browser exposes a function called customElements.define, which permits an element that can be reused to be defined. It takes two arguments:

  1. the element name (should be the exact same as the one used in the HTML code)
  2. the class of the element

We will then create a class in order to have a custom element with our own properties and attributes. This also permits us to add our own event listeners, functions, and behaviors.

You have now created your own custom HTML element. It is good practice to add a constructor to your element class. You will also have to add a super() function in order to make sure you are inheriting all HTMlElement methods, attributes, and properties.

With these additions, your class will look like:

// Creating my own custom HTML element

class HelloWorld extends HTMLElement {
    constructor() {
        super()
    }
}

You can also define custom methods as below:

// Creating my own custom HTML element

class HelloWorld extends HTMLElement {
    constructor() {
        super()
    }

    getId() {
        return this.id
    }
}

Above, we created a method on the element named getId() that will return the id of the element.

You can select your custom element from Javascript just like you would do with any other element using document.querySelector(), document.querySelectorAll(), document.getElementById(), etc. You can also try adding an id attribute, selecting the element using a method of your choice, and calling the getId() method on it.

We have created our own element using just HTML and Javascript, but how can I access lifecycle hooks just like in React or Vue?

Using your defined class, you can also have access to lifecycle methods, which allow you to execute some piece of code when, for example, the component is connected to the DOM.

Take a look at the example below:

connectedCallback() {
        if (this.hasAttribute("ishidden")) {
            this.style.backgroundColor = "grey"
            this.style.pointerEvents = "none"
        }
    }

The connectedCallback method will be executed when the element is connectedmounted to the DOM. In the example, we are checking if the element has the ishidden attribute and then changing the background color and pointer event. Your final Javascript should now look like:

// Creating my own custom HTML element

class HelloWorld extends HTMLElement {

    constructor() {
        super()
    }
    connectedCallback() {
        if (this.hasAttribute("ishidden")) {
            this.style.backgroundColor = "grey"
            this.style.pointerEvents = "none"
        }
    }

    getId() {
        return this.id
    }

}

customElements.define("hello-world", HelloWorld)

Now we have a basic element that’s working.

It is good to note that connectedCallback() is not the only hook. We also have the disconnectedCallback() and attributeChangedCallback().

What about styling? You can directly access the element using its name in CSS. In my CSS file, I added some basic styling to make it look a little better:

hello-world {
    background-color: red;
    padding: 1em;
    border-radius: 5px;
    position: relative;
    top: 4em;
}

You have reached the end of this post. I hope you enjoyed it. If you did, make sure to give me a follow on Twitter. I usually tweet about tech, experimentations, and tips/advice.

RELATED TAGS

javascript
html
community creator
RELATED COURSES

View all Courses

Keep Exploring