2

Suppose I have the following code:

<ul> 
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

Now when I do, $("ul").clone();, it clones the full ul element (all its children also). I want only to clone <ul> and not its children.

How to do that in jQuery?

I know in pure JavaScript (using cloneNode()), but I can't use this because of additional methods to perform also.

user229044
  • 232,980
  • 40
  • 330
  • 338
Ashish Rawat
  • 3,363
  • 5
  • 29
  • 35
  • Because that is what clone does: [_Create a deep copy of the set of matched elements_](http://api.jquery.com/clone/). See also http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object – Nivas Apr 21 '14 at 14:07
  • 1
    I don't get it? Why can't you do `$( $('ul').get(0).cloneNode() )` ? – adeneo Apr 21 '14 at 14:08
  • If you don't want any of the children, it's much cheaper to just make a new empty `ul`: `$('
      ')` than to clone the element (including its children) and then remove its children, as several answer have suggested.
    – user229044 Apr 21 '14 at 14:08
  • why not? cloning means creating new instance with the same values - and the `children` is one of the values – Yaron U. Apr 21 '14 at 14:08
  • Cloning is by definition going to be a deep copy. Do you want a deep copy? It might be more run-time efficient to only create exactly what you need. – J E Carter II Apr 21 '14 at 14:08
  • @meagar: That wouldn't copy event handlers and other data. Nor would `$( $('ul').get(0).cloneNode() )`. To do it with jQuery, the contents should first be detached. – cookie monster Apr 21 '14 at 14:47

4 Answers4

2

You could empty the element:

$('ul').clone().empty();
Jason P
  • 26,984
  • 3
  • 31
  • 45
0

Use .html('') to empty the contents.Try this:

 $("ul").clone().html('');

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

jQuery clone method creates a deep copy of the element.

Description: Create a deep copy of the set of matched elements.

So with jQuery you want be able to get just the ul.

You have two choices:

  1. Empty the object jQuery returns:

    $('ul').clone().empty();

  2. Use plain Javascript:

    var simpleUl = $($('ul').get(0).cloneNode());

Alessandro Vendruscolo
  • 14,493
  • 4
  • 32
  • 41
0

There are two problems with the given solutions.

  1. They are unnecessarily inefficient by cloning all children and their data.

  2. They use the native clone, which doesn't clone event handers and other data.

If you want to do a shallow clone with jQuery and transfer all data, detach its contents before the clone operation, then replace them after.

// Fetch the ul and detach its contents
var ul = $("ul");
var contents = ul.contents().detach();

// Do the clone, copying its data
var clone = ul.clone(true);

// Reattach the contents
ul.append(contents);

If there are multiple elements, then do this operation in a loop.

cookie monster
  • 10,671
  • 4
  • 31
  • 45