I am a newbie to HTML/Javascript so pardon me if the question is very simplistic. I am trying to develop a toy HTML app to maintain a todo list. I am not really stuck but would like to hear about some good design decisions for the problem below.
I have a django server which serves me a list of elements in the following form:
<ul>
<li id="todo_1">Get groceries <a class="deletelink" href="/delete/1/">[X]</a></li>
<li id="todo_2">Water plants <a class="deletelink" href="/delete/2/">[X]</a></li>
<li id="todo_3">Repair bike <a class="deletelink" href="/delete/3/">[X]</a></li>
</ul>
I also have a bit of jQuery that is called whenever one of the "[X]" links is clicked, which deletes the parent list element like this:
$(".deletelink").on("click", function (event) {
event.preventDefault();
var parentItem = $(this).parent(); // the problem is here
$.ajax({
... // ajax post request to server here
}).success( function (status, data) {
parentItem.delete();
});
});
Now, the problem is that if I change the structure of the HTML a bit, e.g. doing <div><a class="deletelink" href="/delete/1/">[X]</a></div>
, I have to go and change the javascript as well. So, I figured out another way to do this. Now, each element has its own id as well, like:
<li id="todo_1">Get groceries <a class="deletelink" id="deletelink_1" href="/delete/1/">[X]</a></li>
Upon click, the javascript changes to
var parentItem = $("#todo_" + (/\D+_(\d+)/.exec(this.id)[1]));
So this implicitly binds each deletelink_i
to the todo_i
list item. However this looks very hacky (e.g., now if I have a list within another list, I can't easily get all the items within the first list). My question is that is there a better or easier way to do all this in javascript? If possible, I would really like to keep the HTML rendering on the server side.