Reputation: 661
I am using jquery to extract text of a set of elements into an array and want to sort them after inserting an element into the array. However, the sort is not working (as in the array remains in the same order after the sort). What's wrong? Code excerpt is below:
var sortedList = [];
$("div.resource").each(function(i, item) {
var resource = $(this).html().toLowerCase();
sortedList.push(resource);
})
// Add the new item
sortedList.push(resource_name.toLowerCase());
alert("before sort");
for (var i = 0; i < sortedList.length; i++) {
alert(sortedList[i]);
}
// Sort the list
sorted = sortedList.sort();
alert("after sort");
for (var i = 0; i < sorted.length; i++) {
alert(sorted[i]);
}
Upvotes: 0
Views: 173
Reputation: 84
In addition to the suggestions to use text() instead of html() and to trim the strings, wrap everything in the jQuery Document Ready function which will give the elements and jQuery library time to load (if you haven't already done that).
Beyond that it could be a browser issue. It works for me in chrome using both html() and text(). Though I made sure the elements only have text in them.
Also probably not a huge issue but your .each() method is missing a semi-colon.
Upvotes: 2
Reputation: 6479
You should try this:
var sortedList = [];
$("div.resource").each(function(i, item) {
var resource = $.trim($(this).text()).toLowerCase();
sortedList.push(resource);
})
Upvotes: 2