I’m trying to make a dynamic list with jquery. What i have is an ul element that contains a link and a sub ul element. Like this:
<div id="new_list"></div>
<ul id="old_list" class="listview">
<li>
<a class="list" href="#">List I</a>
<ul class="sub">
<li>1</li>
<li>2</li>
</ul>
</li>
<li>
<a class="list" href="#">List II</a>
<ul class="sub">
<li>1</li>
<li>2</li>
</ul>
</li>
</ul>
What i want to do with this list is:
when user clicks any of these links, the sub ul element’s html( which is the sibling of the link that is just clicked ) should be copied to new_list div and then made visible.
Here is the code:
$("a.list").each(function() {
$(this).click(function() {
var listToShow = $(this).siblings("ul");
$("#new_list").html(listToShow);
$("#old_list").hide();
$("#new_list").show();
return false;
});
});
This code works for all the links for the first time, but when i click the same link again an empty list comes up.
What am i missing?
Thanks.
When you use a DOM element or a jQuery selection in
html, the elements are removed from where they previously were and moved to the new place in the DOM.If you want to copy them to the location, you need to use
.clone:Note also that you don’t need the
eachcall there: the handler is automatically applied to each element in the selection.