Reputation: 813
This is probably a really easy concept I just misunderstand but taking this jsFiddle:
HTML
<nav>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
</nav>
JS
var items = $('ul li').clone();
var cloner = $('ul').clone().addClass('before');
cloner.prependTo('nav');
items.appendTo('ul');
Why is the ul
I clone have items 1,2,3,1,2,3... shouldn't it just be 1,2,3 ???
I'm trying to duplicate the current ul
and add that duplicate before it then duplicating the items in that first list and duplicate the items within it but I end up with the items duplicated in both and I don't want that.
Upvotes: 0
Views: 578
Reputation: 16932
That is because you clone the items. You never remove them from the dom. I think you are looking for detach(). Detach also removes the elements from the dom.
This will also move all the li elements within your ul element. Remember however that this will target all ul elements on your page and move them to nav (make a more specific selector. Like an id or class).
$('ul').detach().appendTo('nav');
Upvotes: 1
Reputation: 40529
// this creates a copy of each li
var items = $('ul li').clone();
// this clones the ul (and its children) and adds the class
var cloner = $('ul').clone().addClass('before');
// the cloned ul (with its children) are prepended to the nav element
cloner.prependTo('nav');
// the copied li are now appended to all found "ul" elements.
items.appendTo('ul');
The quickest way to do what you want is:
$('ul').clone().prepandTo('nav');
or if you really want to clear it out and add them in again:
$('ul').clone().empty().prependTo('nav');
$('li').clone().appendTo('ul:nth-child(1)');
Upvotes: 0
Reputation: 700562
That's because you are apending the items to both lists in the last line. The ul
selector will match both lists.
If you swap the two last lines in the code, you will only add the items to the one list that exists at that time:
var items = $('ul li').clone();
var cloner = $('ul').clone().addClass('before');
items.appendTo('ul');
cloner.prependTo('nav');
http://jsfiddle.net/Guffa/WZykS/5/
Upvotes: 0
Reputation: 8921
I don't see the problem.
items.appendTo('ul');
adds item 1,2,3 to both <ul />
not just the first/last one.
Upvotes: 0
Reputation: 227280
$('ul').clone()
will clone the <ul>
and all its children. So, when you do cloner.prependTo('nav')
you are adding the <ul>
and its <li>
to the DOM.
Then you do items.appendTo('ul')
. This appends the 3 <li>
s that were cloned to all <ul>
s on the page.
There is no need for var items = $('ul li').clone()
or items.appendTo('ul')
.
Upvotes: 1