I can't access this button when I try to access on some other file. It is working when I do it inside first file but not able to do on file 2? BTW, Css is working fine, if I create a CSS file and add some styling to the elements, it works, but not the javascript
file1.js
else {
product_carousel_wrapper.innerHTML = recent.map(productData =>
`
<h1>Hello</h1>
<button class="click">CTest</button>
<h1>Bye</h1>
`
).join('');
}
file2.js
document.querySelector('.click').addEventListener('click', () => {
alert('Heyy');
});
Attach a listener to the wrapper element and use event delegation to catch events from child elements that have been added to the DOM dynamically instead of attaching a listener to each button.
// FILE1
// Cache the wrapper
const wrapper = document.querySelector('.wrapper');
// Add the HTML
wrapper.innerHTML = `
<button>CTest1</button>
<button>CTest2</button>
<button>CTest3</button>
`;
// FILE2
// Add a listener to the wrapper
wrapper.addEventListener('click', handleClick, false);
// Get the textContent (in this example)
// of the button that was clicked
function handleClick(e) {
if (e.target.matches('button')) {
console.log(e.target.textContent);
}
}
<div class="wrapper"></div>