<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>User Profile Template</title> <style> .profile { border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; } </style> </head> <body> <template id="user-profile-template"> <div class="profile"> <img width="300" src="" alt="User Photo" /> <p class="username"></p> <p class="email"></p> </div> </template> <script> const template = document.getElementById("user-profile-template").content; const userData = { username: "John Smith", email: "john.smith@thecompany.com", photoUrl: "https://images.unsplash.com/flagged/photo-1570612861542-284f4c12e75f", }; const clone = template.cloneNode(true); clone.querySelector(".username").textContent = userData.username; clone.querySelector(".email").textContent = userData.email; clone.querySelector("img").src = userData.photoUrl; clone.addEventListener("click", () => { alert("Profile clicked"); }); document.body.appendChild(clone); </script> </body> </html>
An HTML template returns a DocumentFragment. Since only its children are appended to the document, the event listener is not attached to the template. To fix this, the event listener should be attached to the DocumentFragment’s children.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>User Profile Template</title> <style> .profile { border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; } </style> </head> <body> <template id="user-profile-template"> <div class="profile"> <img width="300" src="" alt="User Photo" /> <p class="username"></p> <p class="email"></p> </div> </template> <script> const template = document.getElementById("user-profile-template").content; const userData = { username: "John Smith", email: "john.smith@thecompany.com", photoUrl: "https://images.unsplash.com/flagged/photo-1570612861542-284f4c12e75f", }; const clone = template.cloneNode(true); clone.querySelector(".username").textContent = userData.username; clone.querySelector(".email").textContent = userData.email; clone.querySelector("img").src = userData.photoUrl; // Add the event listener to the profile div instead of the DocumentFragment clone.querySelector(".profile").addEventListener("click", () => { alert("Profile clicked"); }); document.body.appendChild(clone); </script> </body> </html>