Search code examples
javascriptjquerypluginsappenddetach

Removing parent elements and re-appending children


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?


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/