Well I wanna ask something about replaceChild
in here and I was got trouble when I used that function, so the problem is when I have some function addEventListener
on my button, when I was replace the old button to new element then bring back again, my event listener on my old button doesn't work like before, any suggest to keep my event listener work on my button when my button was replace? Oh ya in bellow I will give you all the link of example of my problem, you can access to understand more about my problem, thanks before have a nice day!
I'll put my code in bellow :
const button = document.querySelectorAll('.button');
button.forEach(function (element) {
element.addEventListener('click', function () {
const buttonClass = element.classList;
if (buttonClass.contains('custom')) {
const buttons = document.querySelector('.buttons');
const testElement = document.createElement('p');
testElement.innerHTML = "I'm Paragraph"
buttons.replaceChild(testElement, buttons.lastElementChild);
} else {
const buttons = document.querySelector('.buttons');
const customElement = document.createElement('button');
customElement.className = "button custom"
customElement.innerHTML = "5"
buttons.replaceChild(customElement, buttons.lastElementChild);
}
});
});
document.querySelector('.custom').addEventListener('click', function () {
console.log('you touched me!')
});
<div class="buttons">
<button class="button">1</button>
<button class="button">2</button>
<button class="button">3</button>
<button class="button">4</button>
<button class="button custom">5</button>
</div>