InsertAfter specific item based on identifier

I have two lists of links. I have such that when a user clicks on a link in any list, he moves to another list. Lists get disorganized very quickly, so I would like them to be organized using an identifier.

What I want, when the user clicks on the link, will search the list for the last element whose data-id is less than the link. Then I insert the item after that.

Now, what really interests me is the most efficient (code wise) way to do this with jQuery. I understand that I can do this with $(".added").each() , but that seems very awkward. Is there a better way to use selectors or something else?

 <div class="available"> <h2>Available Groups</h2> <a href="" data-id="1">Group 1<span>Add</span></a> <a href="" data-id="2">Group 2<span>Add</span></a> <a href="" data-id="3">Group 3<span>Add</span></a> <a href="" data-id="4">Group 4<span>Add</span></a> <a href="" data-id="5">Group 5<span>Add</span></a> </div> <div class="added"> <h2>Added Groups</h2> </div> 

Current implementation:

 $(".available a").on("click",function(){ var myID = parseInt($(this).data("id")); var alist = $(".added a"); if (alist.length > 0) { var nodeToInsertAfter; $(".added a").each(function () { if (parseInt($(this).data("id")) < myID) nodeToInsertAfter = $(this) }); if (nodeToInsertAfter) $(this).insertAfter(nodeToInsertAfter); else $(this).prependTo(".added"); } else { $(this).appendTo(".added"); } }); 
+4
source share
2 answers

Here is one way: jsFiddle example

 $(".available a").on("click", function(e) { e.preventDefault(); $('.added h2').after($(this)); var items = $('.added a').get(); items.sort(function(a, b) { var A = $(a).data('id'); var B = $(b).data('id'); if (A < B) return -1; if (A > B) return 1; return 0; }); $('.added h2').after(items); });​ 
+1
source

insertAfter is not a good way, try the following: http://api.jquery.com/appendTo/

0
source

Source: https://habr.com/ru/post/978382/


All Articles