I am trying to create a simple list with the option to add and remove elements, but it seems there are some scope rules about the selectors that I couldn't find in the official documentation. My HTML, including the jQuery is as follows:
$(function() {
$("#add").click(function() {
let val = $("input").val();
if (val !== "") {
let ele = $("<li></li>").text(val);
ele.append("<button class='rem'>X</button>");
$("#mylist").append(ele);
$("input").val("");
// $(".rem").click(function(){
// $(this).parent().remove();
// });
};
});
$(".rem").click(function() {
$(this).parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Add new item">
<button id="add">Add</button>
<ol id="mylist">
</ol>
The commented part is the part that is running properly, but the one that is outside of the click function for the #add element is not working.