As I understand it, reading the documentation for JS, the "array" of DOV elements elongated by JS, for example, is called a "collection" for certain attributes. The most interesting thing for me is that console.log() displays them as an array (square brackets), but typeof() explicitly says that this is an object. Accordingly, if the collection is an object, then the methods available to the regular array are not available.
Now more to the point. I have HTML about this content:
<a data-sort="3">link</a> <section data-sort="4">section</section> <div data-sort="2">block</div> <a>just a link, without data-sort</a> <span data-sort="1">line</span> JavaScript pulls all elements on the page that have a data-sort attribute:
collection = document.querySelectorAll("[data-sort]"); Now the elements are written in the order in which they appear on the page (3, 4, 2, 1). But I need them in the collection to be stored in the order specified in the data-sort attribute itself.
I decided to use the sort() function. But this feature is only available for arrays. Trying to do this:
collection.sort(function(a, b) { return a - b; }); Uncaught TypeError: collection.sort is not a function
This is understandable, because we are trying to sort the nodes (nodes), and the nodes are no more and no less than each other. It is necessary to sort by attribute (in which the necessary order is written). Let's get an array of attributes:
dataAttrs = []; collection.forEach(function(item, i, coll) { dataAttrs[i] = item.getAttribute("data-sort"); }); Now we have an array of the form 3, 4, 2, 1. It can already be sorted:
dataAttrs.sort(function(a, b) { return a - b; }); Is done. In total, my solution took quite a lot of space, and in the end we have a sorted array of attributes and an unsorted collection of elements.
Question: how to improve this code and still not sort the array of attributes by values (ascending), but the collection itself, based on its attributes?
typeof []:) - Grundytypeof([])will also give object? Well then, I will tell you that I will not be surprised, becausetypeof(null)will also give an object! Let it be a bug. - smellyshovel 8:04 pm