Source Code:
(back to article)
Submit
Result:
Report an issue
<body> <div id="template-container"> <!-- Button Template --> <template id="button-template"> <button id="show-content-btn">Add a content card</button> </template> <!-- Content Template --> <template id="content-template"> <div class="content"> <h2>Dynamic Content</h2> <p>This content is added dynamically when the button is clicked.</p> </div> </template> </div> <div id="button-container"> <!-- Button will be inserted here --> </div> <div id="content-container"> <!-- Content will be displayed here --> </div> <script> // Function to display template content function displayTemplateContent() { // Get the content template const contentTemplate = document.getElementById('content-template'); const contentClone = document.importNode(contentTemplate.content, true); // Display the cloned content document.getElementById('content-container').appendChild(contentClone); } // Insert the button template into the DOM function insertButton() { // Get the button template const buttonTemplate = document.getElementById('button-template'); const buttonClone = document.importNode(buttonTemplate.content, true); // Add event listener to the button buttonClone.querySelector('#show-content-btn').addEventListener('click', displayTemplateContent); // Insert the button into the DOM document.getElementById('button-container').appendChild(buttonClone); } // Call the function to insert the button when the page loads insertButton(); </script> </body>