Custom HTML Elements
Overview
In this lab, you'll work with Custom Elements API to create a custom HTML element named my-card
. This element will extend a 'div' HTMLElement. You will use a constructor to create a shadow root for your custom element, set the color of the my-card
element to blue, and finally add an h1
element with the text 'Hello, World!'.
Concepts
This lab primarily explores Custom Elements API, part of Web Components technologies. The key concepts required for this lab include:
- Custom Elements: This allows developers to define their own custom HTML tags.
- Shadow DOM: This provides encapsulation by allowing attachment of a hidden separated DOM to an element.
- HTMLElement: The base class for all HTML elements
If you're hearing about Custom Elements for the first time, you can read about them on MDN Docs first.
Steps
Follow these detailed steps to implement the task:
-
Create the 'MyCard' class: Begin by defining
MyCard
as a class that extends theHTMLElement
class using ES6. Make sure that this class will form the blueprint for your custommy-card
element. -
Add a constructor: Within the 'MyCard' class, declare a constructor that calls the
super()
function to call the parent class (HTMLElement
) constructor. -
Create a Template and Attach to the Shadow Root: Inside the constructor, create a
template
element and set itsinnerHTML
with the desired content. Finally, attach thetemplate.content.cloneNode(true)
to thethis.shadowRoot
. -
Define the Custom Element: After creating the 'MyCard' class, you need to define your custom element. This is done using
customElements.define()
, where the first parameter is the name of your element and the second is the class that controls its behavior.
Hints
- Remember that your innerHTML should include a
style
tag that sets the color of themy-card
element to blue and anh1
with the text 'Hello, World!'. - Don't forget to use
attachShadow()
with{mode: 'open'}
to create a shadow root. - When appending the template content to the shadow root, use
.cloneNode(true)
as this performs a deep clone of the node, including all its child elements. - To define your custom element, ensure that the name 'my-card' contains a dash (-). This is a requirement for the custom elements' naming convention.
All the best!