Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to sort elements of a class

Tags:

javascript

I have a blog which produces a list like this on a 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 reorder the divs on the page using javascript.

Firstly, to see how it works, an alphabetical sort. (That may be enough for this question). But secondly (what I really want to do) sort them by "age". I have an array of each person's name and age which I can reference. Is this even possible?

I found this when looking for finding by class

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

The sorted output could be on the same page, or on a different page - it doesn't matter. thanks for any help. I know very little about javascript.

I'd like to sort in the order 1) Andy, Bert, Chas, Dave (i.e. "alphabetically) producing:

<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 ideally

2) By their ages, 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>
like image 968
Gabe Avatar asked Dec 28 '22 07:12

Gabe


1 Answers

While I'm not entirely sure what you intend to sort by this 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;
}

This method is currently limited to dealing with a question specific selector but it is fairly flexible. For example both of the following are applicable

sortMyEntries("id");  //Sort blog entries by DOM object id
sortMyEntries("innerHTML");  //Sort blog entries by DOM object innerHTML
like image 128
CBusBus Avatar answered Jan 13 '23 23:01

CBusBus