Using Custom Elements
For this reason, Web Components have Custom Elements. We're going to define a custom tag called <my-greeting>
that the browser will automatically replace with our template—just like any other tag in HTML.
Our greeting.html
file will include one extra element, selectable by ID, that will be customizable by one of the element's attribute. The same ID will be used in every instance of <my-greeting>
that is correct and doesn't collide because each element instance has it's own Shadow DOM:
<!-- web/greeting.html --> <template> <style> h1 { color: yellow; } h2 { color: red; } </style> <h2>Template</h2> <p id="content">Lorem ipsum</p> </template>
The body for index.html
is going to be even simpler than before:
<body> <h2>Hello, world!</h2> <button>Add</button> <my-greeting></my-greeting> <my-greeting custom-attribute="Hello"></my...