Javascript: how to sort class elements

I have a blog that creates a list like this on the php / html page

<div id="unique-id-4" class="blog-entry">Bert blah blah</div> <div id="unique-id-2" class="blog-entry">Andy blah blah</div> <div id="unique-id-3" class="blog-entry">Chas blah blah</div> <div id="unique-id-1" class="blog-entry">Dave blah blah</div> 

I want to change the order of sections on a page using javascript.

First , to see how it works, alphabetically sort . (This may be enough for this question). But secondly (what I really want to do) is to sort them by age . I have an array of the name and age of each person I can refer to. Is it possible?

I found this when searching by class

var content = document.getElementsByClassName('blog-entry')

Sorted output can be on one page or on another page - it does not matter. Thanks for any help. I know very little about javascript.

I would like to sort in order 1) Andy, Burt, Hour, Dave (ie "Alphabetically"):

 <div id="unique-id-2" class="blog-entry">Andy blah blah</div> <div id="unique-id-4" class="blog-entry">Bert blah blah</div> <div id="unique-id-3" class="blog-entry">Chas blah blah</div> <div id="unique-id-1" class="blog-entry">Dave blah blah</div> 

and perfect

2) By age, where in a separate array: Andy = 42, Bert = 18, Chas = 73, Dave = 56; producing

 <div id="unique-id-4" class="blog-entry">Bert blah blah</div> <div id="unique-id-2" class="blog-entry">Andy blah blah</div> <div id="unique-id-1" class="blog-entry">Dave blah blah</div> <div id="unique-id-3" class="blog-entry">Chas blah blah</div> 
+4
source share
6 answers

So far I'm not quite sure what you are going to sort on this issue, should cover all angles.

 /*Sort my entries sortProperty = DOM object property that is to be used to sort in ascending order */ function sortMyEntries(sortProperty) { var blogEntries = document.getElementsByClassName("blog-entry"); blogEntries = Array.prototype.slice.call(blogEntries,0) blogEntries.sort(function(a,b) { return (a[sortProperty] > b[sortProperty]); }) return blogEntries; } 

Currently, this method is limited to considering a specific selector, but it is quite flexible. For example, both of the following conditions apply:

 sortMyEntries("id"); //Sort blog entries by DOM object id sortMyEntries("innerHTML"); //Sort blog entries by DOM object innerHTML 
+3
source

Using magic or unsupported methods:

 var elements = document.getElementsByTagName('div'); var filtered = []; for (var i = 0; i < elements.length; i++) { if (elements[i].className === "blog-entry") { filtered.push(elements[i]); } } var sorted = filtered.sort(function (a, b) { return a.innerHTML > b.innerHTML; }); var parent = elements[0].parentNode; for (i = 0; i < sorted.length; i++) { parent.appendChild(sorted[i]); } 

Jsfiddle demo

Node Information

<h / "> To sort the array:

 var people = [{name: "Andy", age: 20}, {name: "Bob", age: 67}]; var sorted = filtered.sort(function (a, b) { return people[a.innerHTML].age > people[b.innerHTML].age; }); 
+3
source
  • var content = document.getElementsByClassName('blog-entry') will provide you with a node list of the HTMLElement object in the content.
  • Convert it to Array .
  • Sort it using the Array.sort function.
  • In the callback, compare the objects using their innerHTML property.

http://jsfiddle.net/myk2X/3/ is a working example. The silver container contains the original objects, and the light green container saves the result.

+2
source

It depends on how your arrays are stored (does unique-id-X match ages[X] ?), But here's the general method: pass the custom comparison function Array.sort .

 function toArray(obj) { var r = [], i = 0, l = obj.length; for(; i < l; i++) { if(i in obj) { r[i] = obj[i]; } } return r; } var elements = toArray(document.getElementsByClassName('blog-entry')); // Doesn't have full browser support, so you might want to use jQuery, eg here. var ages = [...]; var names = [...]; elements.sort(function(element1, element2) { var index1 = elements.indexOf(element1); var index2 = elements.indexOf(element2); // Sort by name first: if(names[index1] < names[index2]) { // Can do case-insensitive comparison here, too. return -1; } else if(names[index1] > names[index2]) { return 1; } else if(ages[index1] < ages[index2]) { // Names were equal, sort by age. return -1; } else if(ages[index1] > ages[index2]) { return 1; } else { // They're equal. return 0; } }).forEach(function(element) { // This is where the magic happens! appendChild() is just called in order. // The best part is that it looks like it does almost nothing. element.parentNode.appendChild(element); }); 

Of course, there are two things that may not work in IE. (Happy Raynos?). One of them is document.getElementsByClassName , and the other is Array.forEach . They are not supported in some browsers, i.e. in IE. Here's the script compatibility for Array.forEach :

 if(![].forEach) { Array.prototype.forEach = function(action, thisArg) { for(var i = 0, l = this.length; i < l; i++) { if(i in this) { action.call(thisArg, this[i], i, this); } } }; } 
+1
source

First, content is not an array here. This is a NodeList. So, the steps for this.

  • Convert NodeList to Array
  • Array Sort
  • Delete all blog entries
  • Add from sorted array

     <div id="blogs"> <div id="unique-id-4" class="blog-entry">Bert blah blah</div> <div id="unique-id-2" class="blog-entry">Andy blah blah</div> <div id="unique-id-3" class="blog-entry">Chas blah blah</div> <div id="unique-id-1" class="blog-entry">Dave blah blah</div> </div> var blogs = document.getElementById("blogs"); var blogEntries = blogs.getElementsByClassName('blog-entry'); blogEntries = Array.prototype.slice.call(blogEntries); if(blogEntries && blogEntries.length){ blogEntries.sort(sortBlogs); while (blogs.hasChildNodes()) { blogs.removeChild(blogs.lastChild); } while(blogEntries.length){ var blogEntry = blogEntries.shift(); blogs.appendChild(blogEntry); } } function sortBlogs(a, b){ var aid = parseInt(a.id.replace("unique-id-", "")); var bid = parseInt(b.id.replace("unique-id-", "")); return aid - bid; } 

See the demo here: http://jsfiddle.net/diode/8W6AU/7/ Change the sortBlogs function for the required sort. Now it uses the identifier for sorting.

+1
source

It seems like the perfect opportunity to use jQuery and the TinySort string plugin .

0
source

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


All Articles