I have a markup like this:
<div class="sentence">
<ul title="list 3">
<li>
<ul title="list 1">
<li> A </li>
<li> B </li>
</ul>
</li>
<li>
<ul title="list 2">
<li> 1 </li>
<li> 2 </li>
</ul>
</li>
</ul>
<ul title="list n">
.....
</ul>
</div>
I have a function that makes some changes into the elements inside the list. This function is quite large, so to illustrate the problem it could simplify to something like this:
$("div.sentence ul").each(function() {
var mid = $(this).children("li").map(function() {
return $(this).text();
}).get().join(',');
$(this).replaceWith(mid);
});
As you can see, this function has no sense. That’s just an example in order to show some example. Probably, that doesn’t work.
The problem is that function works only when I have only a list (ul). When I have more than one list it doesn’t work because $("div.sentence ul") returns a list of ul elements where the first one is the outer ul and the last one is the last one in reading order (I believe, also I don’t know if this order is guaranted or if it will change in the next Jquery version).
The question is I need to get first the inner lists (not a problem the order) and then the outer ones. For instance, in this example, I need to get the list tittled “list 1”, then “list 2” and the last one should be “list 3”. Is possible to get the *ul*s in this order?
Take a look at this JSFiddle.
Basically, you need a Depth-first traversal (Postorder).
I played a bit with the selectors, mainly with the child-selector to get only the children of the next level, not all until the leaves, this for every ul: