Intermediate LevelHTML & Semantic Web
How do Custom Elements allow defining reusable HTML tags via JavaScript?
❓ Interview Prompt: Explain customElements.define(), autonomous custom elements vs customized built-in elements, and hyphens in tag names.
The Custom Elements API is a key Web Components standard allowing developers to create custom HTML tags with custom behavior:
Rules:
1
Must Contain a Hyphen: Custom tag names MUST contain at least one hyphen (e.g. '<user-card>') to distinguish them from native HTML elements.
2
Extend HTMLElement: Class extends 'HTMLElement' and is registered via 'customElements.define("user-card", UserCard)'.
Code Implementation Example
html
<script>
class UserCard extends HTMLElement {
connectedCallback() {
this.innerHTML = '<h3>User Profile Component</h3>';
}
}
customElements.define('user-card', UserCard);
</script>
<!-- Custom Tag in HTML -->
<user-card></user-card>💡Defining and registering a custom HTML element via Custom Elements API.
🎯 Interview Key Takeaway
Custom element tag names must contain a hyphen (e.g. <user-card>) to prevent collisions with native W3C tags.
#Custom Elements#Web Components#HTMLElement#Intermediate
Back to all HTML & Semantic Web Questions→