Return WebComponent (WC01)


<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Web Component Example</title> <style> /* Global style */ body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; } button { padding: 10px 20px; font-size: 16px; cursor: pointer; } </style> </head> <body> <!-- Button to attach the Web Component --> <button id="attach-button">Attach Web Component</button> <!-- Root element where the Web Component will be attached --> <div id="root"></div> <script> // Define the Web Component class MyComponent extends HTMLElement { constructor() { super(); // Attach a shadow root const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.innerHTML = ` <style> /* Scoped style */ p { color: green; font-weight: bold; } </style> <p>This is inside a Web Component!</p> `; } } // Register the custom element customElements.define('my-component', MyComponent); // Add interaction: Attach the Web Component when the button is clicked const attachButton = document.getElementById('attach-button'); const root = document.getElementById('root'); attachButton.addEventListener('click', () => { // Create an instance of the Web Component const myComponent = document.createElement('my-component'); // Append the Web Component to the root element root.appendChild(myComponent); // Disable the button after attaching the Web Component attachButton.disabled = true; attachButton.textContent = 'Web Component Attached'; }); </script> </body> </html>
ES6 context:
- (2024) Notes about JS Closures. #ES6
- (2024) Notes about Javascript asynchronous programming. #ES6
- (2022) Modern Javascript books #ES6 #Doc
- (2021) JS learning start point #ES6
- (2021) Maximilian Schwarzmüller Javascript lecture #ES6
- (2021) Javascript interview question from Happy Rawat #ES6
- (2021) Javascript tests #ES6
- (2016) New unique features of Javascript (updated). #ES6
Comments (
)

Link to this page:
http://www.vb-net.com/JavascriptES6/WC01.htm
|