Search code examples
javascriptjquerydomappendclone

Appending div's in certain areas within unordered list


I currently have a standard unordered list, which acts as an accordion menu for my site navigation (Here's my markup in full). I want to provide a more enhanced navigation for browsers that support the new features I will be using (css 3d transforms). For this to work, I need to amend the structure of my code slightly to match the output of the following (i.e. append/clone elements into the structure):

<!-- mp-menu -->
<nav id="mp-menu" class="mp-menu">
<div class="mp-level"> <!--NEW APPENDED ELEMENT-->
    <ul id="demo1" class="nav">
        <li>
            <a href="#">Devices</a>
            <div class="mp-level">
                <h2>Devices</h2> <!--NEW CLONED ELEMENT-->
                <a class="mp-back" href="#">back</a> <!--NEW APPENDED ELEMENT-->
                <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> <!--NEW CLONED ELEMENT-->
                <a class="mp-back" href="#">back</a> <!--NEW APPENDED ELEMENT-->
                <ul>
                    <li><a href="#">National Geographic</a></li>
                    <li><a href="#">Scientific American</a></li>
                </ul>
            </div>
        </li>
</ul>
</div>
</nav>

I want to append the new elements if its possible but this doesn't seem to work correctly:

$( "#mp-menu" ).append('<div class="mp-level">');

To clone the Level 1 link into a H2, I've tried but no luck:

$( "#mp-menu ul li .mp-level" ).clone('<h2>Devices</h2>');

Solution

  • .append() is not the same as string concatenation where you can just add bit and pieces of strings to a dom structure.

    For the first part you can use .wrapInner()

    $('#mp-menu').wrapInner('<div class="mp-level" />');
    

    For the second part use the below .prepend()

    $( "#mp-menu ul li .mp-level" ).prepend(function(){
        return '<h2>' + $(this).prev().text()+ '</h2> <a class="mp-back" href="#">back</a>';
    })
    

    Demo: Fiddle