Adding Content, Styling, and Interactivity
Adding Content
You can add content to your custom element in several ways:
- In the constructor:
class MyElement extends HTMLElement {
constructor() {
super();
this.textContent = 'Hello, World!';
}
}
- Using
connectedCallback
:
class MyElement extends HTMLElement {
connectedCallback() {
this.innerHTML = '<h1>Hello, World!</h1>';
}
}
- Using Shadow DOM:
class MyElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = '<h1>Hello, Shadow DOM!</h1>';
}
}
Styling
You can style your custom elements using several methods:
- External styles: Apply styles from your main CSS file.
- Internal styles: Define styles within the Shadow DOM.
:host
selector: Style the custom element itself from within.
Example of internal styling:
class MyElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `
<style>
h1 { color: red; }
</style>
<h1>Hello, Styled World!</h1>
`;
}
}
Adding Interactivity
You can add interactivity to your custom elements using standard JavaScript event listeners:
class MyButton extends HTMLElement {
constructor() {
super();
this.addEventListener('click', () => {
console.log('Custom button clicked!');
});
}
connectedCallback() {
this.innerHTML = '<button>Click me!</button>';
}
}
customElements.define('my-button', MyButton);