Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to find list items with matching class names in separate unordered lists

I have two unordered lists, each filled with list items that have a DYNAMIC class name. When I say "dynamic" I mean they are not generated by me, but they don't change once the lists have been created. These class names are id's I'm getting from an API, so they're just random numbers. A simple example would be something like...

<ul class="listA">
  <li class="123"></li>
  <li class="456"></li>
  <li class="789"></li>
</ul>

<ul class="listB">
  <li class="789"></li>
  <li class="101"></li>
  <li class="112"></li>
</ul>

What I'm trying to do is compare the two lists, and have any matches be highlighted, in this case the items with the class "789" would match. When I say highlighted, I just mean I'll probably apply some css after a match is found, like maybe a background color or something (not too important yet). The problem really lies in the fact that the lists can be somewhat long (maybe 50 items) and the classes are just random numbers I don't choose, so I can't do any specific searches. Also, there will most likely be cases with multiple matches, or no matches at all.

I'm pretty new to jQuery, so there may be a fairly simple answer, but everything I find online refers to searching by a specific class, such as the .find() method. If anyone needs more info or a better example, I'll be happy to give more info, I'm just trying to keep it simple now.

Thanks so much in advance!

like image 222
user2360621 Avatar asked May 08 '13 02:05

user2360621


2 Answers

var $first  = $('ul.listA li'),
    $second = $('ul.listB li');

$first.each(function(){
    var cls = this.className,
        $m  = $second.filter(function(){
            return this.className === cls;
        });

    if ($m.length) {
      $(this).add($m).addClass('matched');
    }
});

http://jsfiddle.net/b4vFn/

like image 145
undefined Avatar answered Oct 04 '22 22:10

undefined


Try it this way:

    $("ul.listA li").each(function(){
         var listAval = $(this).attr('class');
         $("ul.listB li").each(function(){
            if(listAval == $(this).attr('class')){
              //matched..
              return false; //exit loop..
            }
         }
    }
like image 38
Nikko Reyes Avatar answered Oct 04 '22 21:10

Nikko Reyes