Return ShadowDom (SD01)


<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shadow DOM Example</title> <style> body { font-family: Arial, sans-serif; } </style> </head> <body> <!-- Initial button --> <button id="attach-button">Attach Shadow DOM</button> <!-- Container for the shadow DOM (initially empty) --> <div id="shadow-host" style="display: none;"></div> <script> // Step 1: Select the button and the shadow host const attachButton = document.getElementById('attach-button'); const shadowHost = document.getElementById('shadow-host'); // Step 2: Add a click event listener to the button attachButton.addEventListener('click', () => { // Hide the button attachButton.style.display = 'none'; // Show the shadow host shadowHost.style.display = 'block'; // Step 3: Attach a shadow root to the host element const shadowRoot = shadowHost.attachShadow({ mode: 'open' }); // Step 4: Add content to the shadow DOM shadowRoot.innerHTML = ` <style> /* Scoped styles (only apply inside the shadow DOM) */ p { color: blue; font-weight: bold; } button { background-color: green; color: white; border: none; padding: 10px 20px; cursor: pointer; } </style> <p>This is inside the Shadow DOM!</p> <button id="shadow-button">Click Me</button> `; // Step 5: Access and manipulate elements inside the shadow DOM const shadowButton = shadowRoot.getElementById('shadow-button'); shadowButton.addEventListener('click', () => { alert('Button inside Shadow DOM clicked!'); }); }); </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/SD01.htm
|