0

Can Anybody please explain to me why I am getting this Error? "Uncaught TypeError: Cannot read property 'addEventListener' of undefined". I am trying to add a remove button for each image.

<!DOCTYPE html>
<html>
<head lang="en-us">
    <title>temp.html</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equv="X-UA-Compatible" content="IE=Edge">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

<div class="image">
    <img src="https://via.placeholder.com/150" alt="First">
    <button class="remove">X</button>
</div>
<div class="image">
    <img src="https://via.placeholder.com/150" alt="Second">
    <button class="remove">X</button>
</div>

<script>

var appButtons = document.querySelectorAll(".remove");
for(var i=0; appButtons.length; i++){
    appButtons[i].addEventListener("click", function(){
        var father = appButtons[i].parentElement;
        var grandfather = appButtons[i].parentElement.parentElement;
        grandfather.removeChild(father);
    });
}


</script>
</body>
</html>

1 Answers1

0

Not sure if this part matters:

for(var i=0; appButtons.length; i++){

should be

for(var i=0; i < appButtons.length; i++){

The forEach example below works. It also does not cause postbacks on each button, but the for-loop way does. (Why?)

FWIW: Each element in the for-loop (above) is just an object, but each element in the forEach loop (below) is an [object HTMLButtonElement].


Use forEach. Source.

var appButtons = document.querySelectorAll(".remove");

appButtons.forEach(function(item) {
    item.addEventListener("click", function() {
        var father = item.parentElement;
        var grandfather = item.parentElement.parentElement;
        grandfather.removeChild(father);
    });
});
wazz
  • 4,953
  • 5
  • 20
  • 34
  • `It also does not cause postbacks on each button, but the for-loop way does (Why?)`: The reason is explained here: [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486) – t.niese Jun 11 '21 at 14:50
  • `All along there was a syntax error.` syntax error would result in code not being able to run at all because it cannot be parsed due to an error in the syntax. But the given code is syntactically correct, "only" the logic is flawed. – t.niese Jun 11 '21 at 14:58
  • @t.niese thanks for the comments and the link! – wazz Jun 11 '21 at 20:29