I'm trying to sort an li
elements and get an unexpacted result I need to sort it three times to get it correctly,
where have I mistaken? javascript
var sort_by_name = function(a, b) { return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase(); } $this = $("ol#table1"); var list = $this.children(); list.sort(sort_by_name); console.log(list); $this.html(list);
HTML
<ol id="table1" style="display: block; "> <li class="menu__run">I</li> <li class="menu__run">IXX</li> <li class="menu__run">I</li> <li class="menu__run">I</li> <li class="menu__run">I</li> <li class="menu__run">I</li> <li class="menu__run">I</li> <li class="menu__run">I</li> <li class="menu__run">IXX</li> <li class="menu__run">I</li> <li class="menu__run">I</li> <li class="menu__run">I</li> <li class="menu__run">I</li> <li class="menu__run">I</li> <li class="menu__test">st</li> <li class="menu__test">st</li> <li class="menu__test">st</li> </ol>
fiddle example
Given a list of elements and the task is to sort them alphabetically and put each element in the list with the help of JavaScript. insertBefore() method: The insertBefore() method in HTML DOM is used to insert a new node before the existing node as specified by the user.
Adding the “sortable” class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work. The <th> tag defines a header cell in an HTML table.
There are much better ways to sort.
localeCompare()
is such a comparison function. "#table1"
is a more efficient selector than "ol#table1"
.I would suggest this:
$("div#btn").click(function() { var sort_by_name = function(a, b) { return a.innerHTML.toLowerCase().localeCompare(b.innerHTML.toLowerCase()); } var list = $("#table1 > li").get(); list.sort(sort_by_name); for (var i = 0; i < list.length; i++) { list[i].parentNode.appendChild(list[i]); } });
Which you can see work here: http://jsfiddle.net/jfriend00/yqd3w/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With