jQuery Reordering Nested Menu with detach() problems

Hi everyone,

Having a bit of trouble with some jQuery. I would like to re-order a menu that has nested submenus.

I wanted to reorder by li items that do not have an anchor with a class of linked. So for the list items with no chold a.linked, I wanted to move these all the way to the top of the list, keeping the nexted menu order intact.

I though I could just detach these using jquery and prepend them to the list but the ordering has gone bonkers, and the nested structure is gone.

If anyone could take a look at my code I would be so grateful.

The correct re-ordered list should be:


(With all nested ULs intact and in order)

My code is as follows.

Thanks so much.

<!DOCTYPE html>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
<div id="food">
		<li><a class="linked" href="#">Cheese</a>
				<li><a href="#">Cheddar</a></li>
				<li><a href="#">Stilton</a></li>
				<li><a href="#">Roquefort</a></li>
		<li><a class="linked" href="#">Bread</a>
				<li><a class="linked" href="#">Granary</a></li>
				<li><a class="linked" href="#">Wholemeal</a></li>
				<li><a href="#">White</a></li>
		<li><a href="#">Pasta</a>
				<li><a href="#">Fusili</a></li>
				<li><a href="#">Penne</a></li>
				<li><a href="#">Conchiglie</a></li>
		<li><a href="#">Soup</a>
				<li><a href="#">Stilton &amp; Broccoli</a></li>
				<li><a href="#">Wild Mushroom</a></li>
				<li><a href="#">Minestrone</a></li>

var menuReorder = {
	init: function() {
		$('#food ul:first li a:not(.linked)').parent().detach().prependTo('#food ul:first');



Use > to ensure that more deeply nested elements are not affected
#food ul:first>li>a:not(.linked)’

You can also do without the .detatch() method, because when there is just one target, prepend moves the elements.

Thanks Paul, that’s great :slight_smile: