remove only the div inside the parent div

In this websites the user can add as much boxes as he wants, and every box contains a green and blue small boxes, the user should be able to click the blue box to remove the green box. the issue is that every time I click the blue box it doesn’t remove the green box unless there is only one parent box is made. I have tried a lot of ways but nothing is working.

let count = 0;
function addBox() {
    let box = `
    <div class="box">
        <div class="lbox" id="lbox">

        </div>
        <div class="rbox" id="rbox">

        </div>
        <h1>
            ${count}
        </h1>
    </div>
    `
    $(`#boxes`).append(box);

    document.getElementById("lbox").addEventListener("click", function() {
        rbox.remove();
    })

    count++;
}

Answer

If you have more than one parent box you need to iterate over each one. You need to do something like;

let boxes = document.querySelectorAll('.box');
boxes.forEach(function(box){
box.querySelector('lbox').addEventListener('click',function(){
box.remove();
});
})

I haven’t tested this, but the key part is the forEach function. This means everything you do inside the function is scoped to that box.

Leave a Reply

Your email address will not be published. Required fields are marked *