A
A
AndreyVolkov722021-07-10 17:52:12
JavaScript
AndreyVolkov72, 2021-07-10 17:52:12

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>


Function to create a block in html on click
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>
            `
        }
    })


Just in case, here is the block removal function
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

1 answer(s)
7
7rows, 2021-07-11
@AndreyVolkov72

Hold, here is a description of what you need to use Delegation
You need to hang an event on the parent and then it will process children
Well, either when you insert an element, call a new listener for this element

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question