Search code examples
jqueryclonechildren

Jquery Clone direct children of element only


I am trying to clone the first level of an unordered list only and not any children beyond that. My list is as follows.

<ul class='leftNav'>
    <li>A</li>
    <li>D</li>
    <li>C<ul>
         <li>1</li>
         <li>2</li>
         <li>3</li>
    </li>
    <li>D</li>
</ul>

I am using the following to clone list items but this is cloning everything:

var leftNav = $(".leftNav").children().clone();

What I would like is just this:

<li>A</li>
<li>D</li>
<li>C</li>
<li>D</li>

Is this possible with jQuery?


Solution

  • You can do it with:

    var leftNav = $('.leftNav > li').clone().find('ul').remove().end()
    

    jsFiddle example