Best way to reorder dom elements based on json data

As soon as I create a base of dom elements on json data using jtemplates, the best way to reorder these elements is based on changes in json data (sorting, filtering, etc.).

+4
source share
3 answers

So, the method that I am using to solve this problem right now, I have added a numbered index to each of my html template sections, for example:

<div id="list"> <div id="items-start"></div> {#foreach $T as item} <div id="item-{$T.item$index}" class="item"> ...lots of stuff... </div> {#/for} </div> 

Then in my json elements, I added the InitialIndex attribute to keep track of which dom element is associated with each element in json. Thus, after making any changes to my json data, I can call this simple function to apply the changes to dom:

 function applyListChanges(items) { $('.item').hide(); for (var item in items) { var index = items[item].InitialIndex; $('#items-start').append($('#item-' + index)); $('#item-' + index).show(); } } 

Please let me know if you have a better solution.

+1
source

The cleanest and easiest way to do this would be as follows:

1) Reorder / sort the list of JSON objects 2) Clear the DOM list (or delete the list depending on your jTemplate), something like this

 $('#list').html(''); 

3) Then re-populate the list by re-running jTemplate in the JSON object.

Keep in mind that rendering a DOM list using a template engine is quick, makes your code much cleaner, and does not require complex logic to map JSON objects to their DOM equivalent

+1
source

Create a new element, add child elements to this element, add a parent element to the DOM.

0
source

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


All Articles