简体   繁体   中英

innerHTML population through Javascript is not working in IE9

I have a HTML form in which there is a + tag. I would like to sort the list of options through Javascript. I wrote a code which works in Chrome, Firefox, Safari and Opera but doesn't work in Internet Explorer. I am pasting the Javasript code below. Is something missing in my code?

window.onload = function () {
categoryOptions = $('category').innerHTML;
$('category').innerHTML = sortCategoryOptions(categoryOptions);
};

Function definition for sortCategoryOptions() is given below:

function sortCategoryOptions(categoryOptions) {
var eachOption = categoryOptions.split('</option>');
for (var i = 0; i < (eachOption.length - 1); i++) {
    eachOption[i] = eachOption[i] + '</option>';
}
eachOption.sort();
optionsSorted = '';
for (var i = 0; i < eachOption.length; i++) {
    optionsSorted = optionsSorted + eachOption[i];
}
return optionsSorted; 
} 

categoryOptions field has following content

<option>Option3</option>
<option>Option1</option>
<option>Option2</option>
<option>Option4</option>

Expected output

For starters, you are literally looking for a <category> tag, which I'm fairly sure was not your intent. Disregard, as pointed out in comments it looks like $ is an alias of document.getElementById here, not jQuery .

Aside from that, using innerHTML to sort is a horrible idea, even more so because you're relying on </option> to not be changed by the browser's parser (which it invariably will, to </OPTION> )

So, with that in mind, and the assumption that you are working on <select id="category"> , give this a try:

window.onload = function() {
    var sel = document.getElementById('category'),
        arr = [].concat.apply([],sel.children), // convert NodeList to array
        l = arr.length, i;
    arr.sort(function(a,b) {return a.text < b.text ? -1 : 1});
    for( i=0; i<l; i++) sel.appendChild(arr[i]);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM