I have current list look like:
You can achieve the effect you're looking for by using the following logic.
.find('ul:empty').remove()).In the example below I have favoured Native DOM API methods instead of their jQuery counterparts in a few instances because:
$(this).append('
') returns $(this) instead of the newly created list. The work around is to add another line of code, or just use the DOM API this.appendChild($('')[0])
which does return the newly created list. And...var prev;
$('.menu li').each(function(){
if(/^_/.test(this.textContent) && prev) {
prev.appendChild(this);
} else {
prev = this.appendChild($('')[0]);
}
}).find('ul:empty').remove();
The example above results in the following HTML structure: