How may I sort a list alphabetically using jQuery?

后端 未结 10 2141
灰色年华
灰色年华 2020-11-21 23:13

I\'m a bit out of my depth here and I\'m hoping this is actually possible.

I\'d like to be able to call a function that would sort all the items in my list alphabeti

10条回答
  •  逝去的感伤
    2020-11-21 23:54

    improvement based on Jeetendra Chauhan's answer

    $('ul.menu').each(function(){
        $(this).children('li').sort((a,b)=>a.innerText.localeCompare(b.innerText)).appendTo(this);
    });
    

    why i consider it an improvement:

    1. using each to support running on more than one ul

    2. using children('li') instead of ('ul li') is important because we only want to process direct children and not descendants

    3. using the arrow function (a,b)=> just looks better (IE not supported)

    4. using vanilla innerText instead of $(a).text() for speed improvement

    5. using vanilla localeCompare improves speed in case of equal elements (rare in real life usage)

    6. using appendTo(this) instead of using another selector will make sure that even if the selector catches more than one ul still nothing breaks

提交回复
热议问题