Question

I have a navigation that's a unordered list, here's the simple structure I'm following / have to follow for my jQuery plugin to work correctly, therefore making this code structure a necessity:

<nav id="mp-menu" class="mp-menu">
<div class="mp-level">
    <ul id="demo1" class="nav">
        <li>
            <a href="#">Devices</a>
            <div class="mp-level">
            <h2>Devices</h2>
            <a class="mp-back" href="#">back</a>
            <ul>
                <li><a href="#">Mobile Phones</a></li>
                <li><a href="#">Televisions</a></li>
                <li><a href="#">Cameras</a></li>
            </ul>
            </div>
        </li>
        <li>
            <a href="#">Magazines</a>
            <div class="mp-level">
                <h2>Magazines</h2>
                <a class="mp-back" href="#">back</a>
                <ul>
                    <li><a href="#">National Geographic</a></li>
                    <li><a href="#">Scientific American</a></li>
                </ul>
            </div>
        </li>
        ...
   </ul>
</div>
</nav>

I need to provide a fallback and I have selected another jQuery plugin that needs to use a different structure to the above. I need to remove the DIV's with classname .mp-level but still keeping all unordered lists including .mp-level child lists.

The result will just be unordered lists without headings and DIV'S. My code below is removing the correct elements but my issue is with re-inserting the child unordered lists (specifically level 2):

$( "#demo1 h2, .mp-back" ).remove();
$( ".mp-level ul li .mp-level" ).detach();
$( ".mp-level ul li" ).append('.mp-level ul li .mp-level ul');

Anyone got any advice how to re-insert child UL's after I have removed their parents?

Was it helpful?

Solution

you can do this

$("#mp-menu").find(".mp-level").each(function(i,n){//each ".mp-level"
    $(n).parent().append($(n).children());//append children to parent
    $(n).remove();//remove actual div
});        

http://jsfiddle.net/WBWwG/

OTHER TIPS

You can save the detached nodes (wrapped inside a jQuery object) by assigning them to a variable and then using that variable in the .append() call.

Something like this:

// this selector doesn't select anything from the example html, btw
var $mp_level = $( ".mp-level ul li .mp-level" ).detach(); 
$(".mp-level ul li").append($mp_level);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top