sort select menu alphabetically?

前端 未结 4 1204
Happy的楠姐
Happy的楠姐 2021-01-12 00:46

I\'ve got the following select menu (jsFiddle):

 element's children NodeList to an array.  However, this doesn't work in Internet Explorer 8 and lower so I changed it to extract, sort and then re-insert:

var sel = document.getElementsByTagName("select")[0],
    opts = [];

// Extract the elements into an array
for (var i=sel.options.length-1; i >= 2; i--)
    opts.push(sel.removeChild(sel.options[i]));

// Sort them
opts.sort(function (a, b) { 
    return a.innerHTML.localeCompare(b.innerHTML);
});

// Put them back into the 
                        
    
提交评论

提交回复
热议问题