Gaurav
Gaurav

Reputation: 8487

jquery 2 divs children comparison

I have 2 elements ( div ) :

I

<div id="1">
 <div >
  <img /> <img />
  <span> </span>
   . 
   .
 <div>
 <div>
  <p></p>
  .
  .
 </div> 
 .
 .
</div>

II

<div id="2">
 <div >
  <img />
  <span></span>
  <h1></h1>
  . 
  .
 <div>
 . 
 .
</div>

both divs have different number of child and those child further have different number of there subchilds. My question is , i want to compare these 2 div and access all the unsimilar elements present in div#2 in comparison with div#1. How can i do this with using jquery methods and as efficient as possible?

Upvotes: 2

Views: 723

Answers (1)

Sagiv Ofek
Sagiv Ofek

Reputation: 25270

this can be a good start for you:

function compare(o1, o2){
 var arr = [];
 $(o1).each(function(i1){        
     var match = false;
     $(o2).each(function(i2){            
         if ( $("o1:eq("+i1+")").html() == $("o2:eq("+i2+")").html() )
             match = true;
     });
     if ( !match )
         arr.push($("o1:eq("+i1+")")[0]);        
 });
 return arr;
}

you go over each element and look for a match. push all the elements that have no match in array and return the array.
note that it compare the first children of each given object.
to call it:

var diffs = compare(div1,div2);

Upvotes: 1

Related Questions