I have an unordered list, but there are headers within it for different categories.
<ul>
<h2>header1</h2>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<h2>header2</h2>
<li>...</li>
</ul>
I’m trying to loop through them and order them by the date, but the headers are throwing it off.
I’m looping through using:
var list = $('#articleList');
list.children("li").each(function () {
...
}
and I’m using this within the loop to select the one before it:
var prev = $(this).prev("li");
For some reason, prev selects the headers if you are on the list item after the header instead of the list item before them. So my sorting ends up being correct within the headers, but I need the whole thing to be ordered, not just in sections.
This will have to do with the HTML parsing. By specification, lists may only contain
<li>elements and nothing else. So, your browser will build a different DOM, e.g. by wrapping the headings into list items (HTML5 wil specify what exactly to do with invalid HTML). Use your DOM inspector to view the actual DOM tree (context menu -> Inspect element).