EDIT: for a general solution, this worked for me. Event binding on dynamically created elements?
So I have a interface that kind of looks like this:
User can toggle to show or hide the sublists. I used jquery to select the toggle buttons for them to work:
$(".dropdownBtn").click(function(){
//rotate the button
$(this).parent().toggleClass("caret-down");
//hide the sublist
$(this).closest("li").find(".active").toggleClass("nested");
})
They can also add new sub_elements to each element. For example, like this:
$(".fa-plus-square").click(function(){
//if there's no new list, create a new unordered list
if ($(this).closest("li").find("ul").length == 0){
$(this).parents("li").append(newUL);
//and add a toggle button
$(this).parent().prepend(toggleBtn);
}
//add the element
$(this).closest("li").find("ul").append("<li>newElement</li>")
})
But then the newly added toggle button under element 3 wouldn't respond. I believe that I need to "bind" the newly added button. But I'm not sure what's the best practice to do so.