manikanta gowda manikanta gowda - 4 months ago 9
jQuery Question

How to display list content in alphabetically?

I have a list of brands in my store which I want to display those brands in alphabetically. Here is my code:

<ul class="brand-list block-grid three-up mobile one-up">
<li class="vendor-list-item">
<a href="{{ link_item.url }}" title="{{ link_title }}">
{{ link_title }}
</a>
</li>
</ul>


I have used some Javascript functions but nothing works fine for me.

var items = $('.brand-list li').get();
items.sort(function(a, b) {
var keyA = $(a).text();
var keyB = $(b).text();

if (keyA < keyB)
return -1;
if (keyA > keyB)
return 1;
return 0;
});

var ul = $('.brand-list');
$.each(items, function(i, li){
ul.append(li);
});


that script is not working i hope because of my brands are appearing inside the tag

any help?

Answer

Sometimes Your class will not works so need to use ID

try with this code

  <ul id="brand-list block-grid three-up mobile one-up">
<li class="vendor-list-item"> 
    <a href="{{ link_item.url }}" title="{{ link_title }}">
        {{ link_title }}
    </a> 
</li>

    var items = $('.brand-list li').get();
   items.sort(function(a, b) {
   var keyA = $(a).text();
   var keyB = $(b).text();

if (keyA < keyB) 
    return -1;
if (keyA > keyB) 
    return 1;
return 0;
    });

var ul = $('.brand-list');
 $.each(items, function(i, li){
ul.append(li);
  });

hope will helps

Comments