views:

130

answers:

1

Hi, I have a web page that contains two lists (Unorders lists), I have to move items from list 1 to list 2 but to filter out items that are already in list 2. I'm using JQuery as js library. I know I can select all items to be moved to list 2, loop one by one and check if alredy exists in list 2, but was wandering if there is a way to do it in less lines of code using filter, :not, :has ... Here is a html structure:

  <ul id="ulList_1">
     <li>
        <a href="#">item 1</a>
     </li>
     <li>
        <a href="#">item 2</a>
     </li>
  </ul>

  <ul id="ulList_2">
     <li>
        <a href="#">item 2</a>
     </li>
     <li>
        <a href="#">item 3</a>
     </li>
     <li>
        <a href="#">item 4</a>
     </li>      
 </ul>

So, in this scenario I want to select only "item 1" since "item 2" already exists in "ulList_2", and append it to list 2 Thanks

+1  A: 

I would extract first the innerText of the elements of your list 2 to an array using $.map, and then filter the list 1, selecting only the non-existing elements of list 2 using $.inArray:

var list2Items = $('#ulList_2 li > a').map(function(){return $(this).text();}); 
// list2Items will be: ["item 2", "item 3", "item 4"] 

var itemsNotInList2 = $('#ulList_1 li > a').filter(function(){
  return $.inArray($(this).text(), list2Items) == -1; // Select only non-existing
});                                                   // items.
CMS
cool, seems like elegant solution, hope you tested it and works :-)
krul
Yep, I never post untested code :-) http://jsbin.com/ahido/edit
CMS