0

I have this code snippet, I want it to remove the or of itself when I press the 'x' button. I've been fiddling around the for loop, when I delete the first , I can't delete the second, seems like the script just stops/breaks. When I also try to delete the second image, it deletes the first instead.

Basically, I just want the 'x' button to remove to corresponding image it's paired to.

<body>
<div class="image">
    <img alt="First">
    <button class="remove">X</button>
</div>
<div class="image">
    <img alt="Second">
    <button class="remove">X</button>
</div>

<script>
    let btn = document.getElementsByClassName('remove');
    let div = document.getElementsByClassName('image');

    for (let i = 0; i < btn.length; i++) {
        btn[i].onclick = function () {
            for (let j = i; j < div.length; j++) {
               div[j].remove();
               console.log("i:" + i);
               console.log("j:" + j);
            }
        }
    }

</script>
2
  • getElementsByClassName returns a live collection. Either turn it into a (non-live) array, or (easier) access the .parentElement of the button Commented Jul 19, 2022 at 6:42
  • you can just hide it. Right? Commented Jul 19, 2022 at 6:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.