Sorting html blocks JS?

Good day, there are many (about 500) html Blocks with the names of items as you can otsoedinaut them alphabetically?

<div class="slide">
 <div class="good">
 <img class="lazyload" src="img.jpg">
<p>Banana</p>
</div>
</div>
<div class="slide">
 <div class="good">
 <img class="lazyload" src="img.jpg">
<p>cherry</p>
</div>
</div>
<div class="slide">
 <div class="good">
 <img class="lazyload" src="img.jpg">
 <p>blue Curacao</p>
</div>
</div>
<div class="slide">
 <div class="good">
 <img class="lazyload" src="img.jpg">
<p>Tea maker</p>
</div>
</div>
March 23rd 20 at 19:28
3 answers
March 23rd 20 at 19:30
Solution
Collect all the blocks in a dictionary, where the key is word, value is the block.
The keys to sort.
To place the blocks back to the parent of the first of them.
JavaScript code
function resort(selector) {
 const nodeList = document.querySelectorAll(selector);
 const dict = {};
 const parent = nodeList[0].parentNode;
 nodeList.forEach(node => {
 const key = node.querySelector('p').innerText;
 dict[key] = node;
node.parentNode.removeChild(node);
});
 const keys = Object.keys(dict);
 keys.sort().forEach(k => parent.appendChild(dict[k]));
}

resort('.slide');


Working example:
cool, thanks a lot - estefania42 commented on March 23rd 20 at 19:33
March 23rd 20 at 19:32
Solution
as these blocks appear on the page from the database that is from an array?
the correct way is to first sort the array before displaying in the html page
not stupidly crammed with html code, you can shuffle them manually, then it's probably a whole day to spend - estefania42 commented on March 23rd 20 at 19:35
@estefania42, Yes, no, something like this happens
https://codepen.io/anon/pen/qGzxea?editors=1010 - cordelia.Corwin commented on March 23rd 20 at 19:38
@cordelia.Corwin, Wow, cool, thank you very much :-) - estefania42 commented on March 23rd 20 at 19:41
March 23rd 20 at 19:34
Plug any library for parsing HTML, reparse received objects sort and turn them back into HTML so do not shuffle.
I can advise the rules of the library? never used, don't understand which is better - estefania42 commented on March 23rd 20 at 19:37
@estefania42, depending on what you're drinking this script. If Python - take - beautiful soup, if php, try the most simple (in my opinion) old library phpquery. Well this is you need to make a one time only distillery in the sorted view, peresechenii your pattern and all. I understand that these 500 items you have static, not added, do not change and are stored just in the template.

PS. to do this sorting on the front-end funds js after page load, in my opinion, a crutch, because the user can see how the unit blinks (sorted and overwritten) - nafig it is necessary. - Jadyn80 commented on March 23rd 20 at 19:40

Find more questions by tags JavaScript