Answer the question
In order to leave comments, you need to log in
Why doesn't js code work in a block that was created using innerHTML and rendered in html?
Essence
By clicking on the button, a block ("header__basket-item") should be added to the html, in this block, by clicking on the button ("header__btn-delete"), the function of deleting this block from html should occur. But nothing happens.
But when I manually create these blocks in html, everything works, and when a block is added via js, nothing works.
The only thing that "dug" on the Internet is that innerHTML does not always work correctly and you need to somehow draw the
html block differently
<div class="header-basket-content">
<div class="header__basket-item">
<img class="header__basket-img" src="img/mac/mc-little.png" alt="">
<div class="header__basket-text">
<p class="card__title text--margin">Ноутбук Apple MacBook Pro 16 TB i7 2.6/16/512 SSD SG MVVJ2RU/A</p>
<p class="card__price">190 789 ₽</p>
</div>
<img class="header__btn-delete" src="img/backet/trash 3.svg" alt="">
</div>
</div>
const headerItemWrapper = document.querySelector('.header-basket-content');
btn.addEventListener('click', ()=> {
headerItemWrapper.innerHTML += createItemBasket();
function createItemBasket() {
return `
<div class="header__basket-item">
<img class="header__basket-img" src="img/mac/mc-little.png" alt="">
<div class="header__basket-text">
<p class="card__title text--margin">Ноутбук Apple MacBook Pro 16 TB i7 2.6/16/512 SSD SG MVVJ2RU/A</p>
<p class="card__price">190 789 ₽</p>
</div>
<img class="header__btn-delete" src="img/backet/trash 3.svg" alt="">
</div>
`
}
})
const basketItem = document.querySelectorAll('.header__basket-item');
basketItem.forEach(item=> {
let basketBtnDelete = item.querySelector('.header__btn-delete');
basketBtnDelete.addEventListener('click', ()=> {
headerItemWrapper.removeChild(item);
})
})
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question