1

Right now in my code I have a table being dynamically built and then the user enters some data into a field in the table. Afterwards I'd like to present the user with the opportunity to sort the list based on that field. What I'd like to do is use document.getElementsByClassName to grab all of the value fields and then sort them but maintain the object data so something like this.

var posts = document.getElementsByClassName('data');
posts.values.sort();  // I'd like to sort the array by the value of the html objects
for(i=0;i<posts.length;i++){
    //modify table order
}
0

3 Answers 3

2

You'll want to convert the HTMLCollection to an Array first then sort.

var posts = document.getElementsByClassName('data');
var arr = [].slice.call(posts); // convert HTMLColleciton to Array
arr.sort();

EDIT: Sort takes a function as a parameter that will allow you to sort based on an array's property

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming all elements on posts array are input controls having value property, you could simply do

var arr = Array.prototype.slice.call(document.getElementsByClassName('data'));
arr.sort(function(a, b) {
    if (a.value < b.value) {
       return -1;
    }

    if (a.value > b.value) {
        return 1;
    }

    return 0;
});

or even better (thanks @Phil)

arr.sort(function(a, b) {
    return a.value.localeCompare(b.value);
});

Take into account that I'm doing an alphabetical sort. Feel free to do the comparison more appropiated for your scenario

13 Comments

AFAIK you can't use sort directly on a dom collection, don't you need to convert it to an array first?
@Rob M.: you may be right, I'm not very used to getElementsByClassName and assumed it returned an array. Thanks for the feedback
@RobM. is right. You can use the Array.prototype.sort.call(posts, function...). Also, return a.value.localeCompare(b.value) is a simple one-liner
no problem, I would just update your post to be: var posts = Array.prototype.slice.call(document.getElementsByClassName('data')); or go with @Phil's suggestion
@RobM. actually, I think you might need slice to convert it to an array first because sort doesn't return
|
1

document.getElementsByClassName will give you a HTMLCollection Object but not an Array, and HTMLCollection Object do not have sort method

So you should change it into an Array.

var posts = document.getElementsByClassName('data') , arr = [];
for(var i = 0 ; i < posts.length; i++){
    arr.push(posts[i])
}
arr.sort()

2 Comments

What kind of data will be stored when I push the node on? Just the name of the object and it's data?
The data you store will be the same as the node.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.