По иронии судьбы проблема с вашим HTML-комментарием, который рассматривается как часть .innerHTML
.Поскольку первая буква комментария (<
) считается символом ASCII «меньшего размера», чем C
(<
против C
), статья HTML
, содержащая комментарий, сортируется в верхней частисписок в алфавитном порядке.
Простое удаление этого комментария из вашей статьи HTML
приводит к сортировке элементов в соответствии с ожиданиями:
//Script borrowed from: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_list
function sort() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("courses");
switching = true;
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
b = list.getElementsByTagName("LI");
//Loop through all list-items:
for (i = 0; i < (b.length - 1); i++) {
//start by saying there should be no switching:
shouldSwitch = false;
/*check if the next item should
switch place with the current item:*/
if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
/*if next item is alphabetically
lower than current item, mark as a switch
and break the loop:*/
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switch
and mark the switch as done:*/
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
article {
border: 1px solid black;
margin: 10px;
padding: 10px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Sorting Articles</title>
</head>
<body>
<button onclick="sort()">Sort list items</button>
<section>
<h1>All courses:</h1>
<ul id="courses">
<li>
<article>
<h2>HTML (1)</h2>
<p>Some text about the HTML course.</p>
</article>
</li>
<li>
<article>
<h2>CSS (2)</h2>
<p>Some text about the css course.</p>
</article>
</li>
<li>
<article>
<h2>JavaScript (3)</h2>
<p>Some text about the JavaScript course.</p>
</article>
</li>
<li>
<article>
<h2>Ruby (4)</h2>
<p>Some text about the Ruby course.</p>
</article>
</li>
<li>
<article>
<h2>Python (5)</h2>
<p>Some text about the Python course.</p>
</article>
</li>
<li>
<article>
<h2>Java (6)</h2>
<p>Some text about the Java course.</p>
</article>
</li>
</ul>
</section>
</body>
</html>