jquery: find common elements in 2 sets of divs

Posted by tsiger on Stack Overflow See other posts from Stack Overflow or by tsiger
Published on 2010-04-25T14:20:42Z Indexed on 2010/04/25 14:33 UTC
Read the original article Hit count: 149

Filed under:

For a markup like this:

<div id="set1">
 <div id="100">a div</div>
 <div id="101">another div</div>
 <div id="102">another div 2</div>
 <div id="120">same div</div>
</div>  

<div id="set2">
 <div id="105">a different div>
 <div id="101">another div</div>
 <div id="110">more divs</div>
 <div id="120">same div</div>
</div>

As you can see both #set1 and #set2 contain 2 divs with the same id (101, 120). Is it possible somehow with jQuery to find the common elements and add a class to the divs in #set1 that have the same id with divs in #set2?

In other words after the script run the above code would look like this:

<div id="set1">
 <div id="100">a div</div>
 <div id="101" class="added">another div</div>
 <div id="102">another div 2</div>
 <div id="120" class="added">same div</div>
</div>  

<div id="set2">
 <div id="105">a different div>
 <div id="101">another div</div>
 <div id="110">more divs</div>
 <div id="120">same div</div>
</div>

EDIT playing around with it i did something but i am not sure it can go anywhere. I created an array with the ids in both sets and in Firebug i can see an array with the values

 var arrEl = [];
   $('#set1 div, #set2 div').each( function(index) {
    var id = $(this).attr('id');            
    arrEl.push(id);

 //maybe somehow check the array for the values that appear twice, and add the class to the //matching divs?
   });

© Stack Overflow or respective owner

Related posts about jQuery