By right-clicking on each picture, the picture will be removed, and a new item will be created by clicking on the + button.
But the problem is that the new items that are created (appended) could not be removed. Why is this the case?
JavaScript
x
10
10
1
$(document).ready(function() {
2
let nextItem = 4;
3
$(".items div").click(function() {
4
$(this).remove();
5
});
6
$(".btn").click(function() {
7
$(".items").append(`<div id="${nextItem}"><img src="https://picsum.photos/id/${nextItem - 1}/200/100" alt=""></div>`);
8
nextItem++;
9
})
10
});
JavaScript
1
11
11
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
4
<div class="container">
5
<div class="items">
6
<div id="1"><img src="https://picsum.photos/id/0/200/100" alt=""></div>
7
<div id="2"><img src="https://picsum.photos/id/1/200/100" alt=""></div>
8
<div id="3"><img src="https://picsum.photos/id/2/200/100" alt=""></div>
9
</div>
10
<button class="btn">+</button>
11
</div>
Advertisement
Answer
Because those aren’t targeted by the event handler. It doesn’t automatically update the elements which are matching the query selector, it’s the same as if you’d used addEventHandler
– it runs once. (see below where they don’t log a message to the console but the hardcoded ones do).
JavaScript
1
10
10
1
$(document).ready(function() {
2
let nextItem = 4;
3
$(".items div").click(function() {
4
console.log("Event processed");
5
});
6
$(".btn").click(function() {
7
$(".items").append(`<div id="${nextItem}"><img src="https://picsum.photos/id/${nextItem - 1}/200/100" alt=""></div>`);
8
nextItem++;
9
})
10
});
JavaScript
1
11
11
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
4
<div class="container">
5
<div class="items">
6
<div id="1"><img src="https://picsum.photos/id/0/200/100" alt=""></div>
7
<div id="2"><img src="https://picsum.photos/id/1/200/100" alt=""></div>
8
<div id="3"><img src="https://picsum.photos/id/2/200/100" alt=""></div>
9
</div>
10
<button class="btn">+</button>
11
</div>
Instead what I would do is define that removal as a function and re-add it to the new element using the id
:
JavaScript
1
12
12
1
$(document).ready(function() {
2
let nextItem = 4;
3
function removeItem() {
4
$(this).remove();
5
}
6
$(".items div").click(removeItem);
7
$(".btn").click(function() {
8
$(".items").append(`<div id="${nextItem}"><img src="https://picsum.photos/id/${nextItem - 1}/200/100" alt=""></div>`);
9
$(`#${nextItem}`).click(removeItem);
10
nextItem++;
11
})
12
});
JavaScript
1
11
11
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
4
<div class="container">
5
<div class="items">
6
<div id="1"><img src="https://picsum.photos/id/0/200/100" alt=""></div>
7
<div id="2"><img src="https://picsum.photos/id/1/200/100" alt=""></div>
8
<div id="3"><img src="https://picsum.photos/id/2/200/100" alt=""></div>
9
</div>
10
<button class="btn">+</button>
11
</div>