kidA kidA - 6 months ago 22
jQuery Question

Move li elements with certain class into and div

I am trying to use the .append function in jquery.
I have a div with li elements in it. They have different classes, lets say odds and evens.
I would like the li's with the class "odd" moved into another div with li's in it.
How can I do this?
Here is my setup:
Edit. This was in valid markup, I just didn't put all in. Fixed now for others.

<div id="col1">
<ul>
<li class="odd"></li>
<li class="even"></li>
<li class="odd"></li>
<li class="even"></li></ul>
</div>
<div id="col2">
<ul>
<li></li>
</ul>
</div>


So then the output is:

<div id="col1">
<li class="even"></li>
<li class="even"></li>
<li class="even"></li>
<li class="even"></li>
</div>
<div id="col2">
<li class="odd"></li>
<li class="odd"></li>
<li class="odd"></li>
<li class="odd"></li>
</div>

Answer

If you already have <div> elements which you are moving elements into you can try this:

$("#col1 li").each(function(){
    var $li = $(this);
    if ($li.hasClass("odd")) $("#odd").append($li);
    if ($li.hasClass("even")) $("#even").append($li);
});

working example:

http://jsfiddle.net/hunter/jq8bW/