JavaScript to compare two <div> elements with same ID and style them if their contents are different

Related searches

I need to use JavaScript to dynamically style output from a PHP application that displays product information side by side to compare them (I cannot edit this PHP application).

The fields get the same ID for each product (i.e. if comparing two products, I get two occurrences of s with the same IDs, cf1 through cf5).

I tried using querySelectorAll to get an array of the ID occurrences and then moving through them and comparing them, but got nowhere with it.

HTML:

<div class="inner">
  <div class="comparison-div half" id="product-comparison-11">
    <div class="cf field" id="cf-1">
      <div class="cf-label label">Field 1 label:</div>
      <div class="cf-value value">Field 1 value</div>
    </div>
    <div class="cf field" id="cf-2">
      <div class="cf-label label">Field 2 label:</div>
      <div class="cf-value value">Field 2 unique value A</div>
    </div>
  </div>


  <div class="comparison-div half" id="product-comparison-15">
    <div class="cf field" id="cf-1">
      <div class="cf-label label">Field 1 label:</div>
      <div class="cf-value value">Field 1 value</div>
    </div>
    <div class="cf field" id="cf-2">
      <div class="cf-label label">Field 2 label:</div>
      <div class="cf-value value">Field 2 unique value B</div>
    </div>
  </div>

</div>

JS:

var cf1 = document.querySelectorAll("div#cf-1");
var cf2 = document.querySelectorAll("div#cf-2");

for (var i = 0, max = cf1.length; i < max; i++) {
  if (Object.is(cf1[i], cf1[i++]) == false) {
    cf1[i--].style.backgroundColor = "red";
    cf1[i].style.backgroundColor = "red";
  }
}

for (var i = 0, max = cf2.length; i < max; i++) {
  if (Object.is(cf2[i], cf2[i++]) == false) {
    cf2[i--].style.backgroundColor = "red";
    cf2[i].style.backgroundColor = "red";
  }
}

JSFiddle: http://jsfiddle.net/coisos/j45p0adt/

I expected cf2 to get a red background as the contents for each of its occurrences are different. Instead, it seems the code has no effect.

2 problems..

  1. Two different objects will never equal, even. Object.is({},{}) is false.
  2. cf1[i++], this will increase after your index, ++i would be what your after.

So another idea, is get the innerText, this is a string, and string comparisons will work as expected..

if (cf1[i].innerText !== cf1[++i].innerText) {

Updated fiddle -> http://jsfiddle.net/jbv5ywam/

Comparisons, Compare two strings in the current locale: var str1 = "ab"; var str2 = "cd"; var n = str1.localeCompare(str2);. Try it Yourself �. More "Try it Yourself" examples below � The algorithm to compare two strings is simple: Compare the first character of both strings. If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done. Otherwise, if both strings’ first characters are the same, compare the second characters the same way.

you have an error in using your ++ operator. comparing cf[i] and cf[i++] will always result to true, the ++ operator increments the value after the current usage if placed after the variable. same with your -- operator.. so if you want the increment to happen in place, you should place it before the variable like this ++i

JavaScript Comparison and Logical Operators, JavaScript provides three different value-comparison operations: perform a type conversion when comparing two things, and will handle NaN� The simplest and fastest way to compare two arrays is to convert them to strings by using the JSON.stringify () method and then use the comparison operator to check if both strings are equal:

for this Jquery

$(document).ready(function(){
  var $source = $("#product-comparison-11");
  var $target = $("#product-comparison-15");
  
  $target.find("[data-field]").each(function(i, item){
    var field = $(this).data("field");
    
    if($source.find("[data-field='"+ field +"'] .value").html() !== $(item).find(".value").html()){
      $(item).addClass("red")
    }
    
  })
})
.half {
  width: 48%;
  margin: 32px 1%;
  position: relative;
  float: left;
}

.label {
  color: #333;
  width: 25%;
  border-right: solid 1px #ccc;
  font-weight: 600;
  text-align: left;
  background-color: #fbfbff;
  border-bottom: solid 1px #ccc;
  min-width: 159px;
  display: table-cell;
  vertical-align: middle;
}

.value {
  color: #333;
  width: 75%;
  text-align: left;
  overflow: auto;
  display: table-cell;
  vertical-align: middle;
}

.field {
  clear: both;
  position: relative;
  width: 100%;
  border: 1px solid #ccc;
  display: table;
  line-height: 1.2;
  font-size: 95%;
  border-collapse: collapse;
}

.red{
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="inner">
  <div class="comparison-div half" id="product-comparison-11">
    <div class="cf field" data-field="cf-1">
      <div class="cf-label label">Field 1 label:</div>
      <div class="cf-value value">Field 1 value</div>
    </div>
    <div class="cf field" data-field="cf-2">
      <div class="cf-label label">Field 2 label:</div>
      <div class="cf-value value">Field 2 unique value A</div>
    </div>
  </div>


  <div class="comparison-div half" id="product-comparison-15">
    <div class="cf field" data-field="cf-1">
      <div class="cf-label label">Field 1 label:</div>
      <div class="cf-value value">Field 1 value</div>
    </div>
    <div class="cf field" data-field="cf-2">
      <div class="cf-label label">Field 2 label:</div>
      <div class="cf-value value">Field 2 unique value B</div>
    </div>
  </div>

</div>

JavaScript String localeCompare() Method, An iterative comparison of attributes that have primitive values may not be in AngularJS, the angular.equals function will determine if two objects are equal. In Javascript, to compare two arrays we need to check that the length of both arrays should be same, the objects present in it are of the same type and each item in one array is equal to the counterpart in another array. By doing this we can conclude both arrays are the same or not. JavaScript provides a function JSON.

Equality comparisons and sameness, Comparing two dates in JavaScript can be said like this: Compare two dates in terms of which is greater and which is smaller. In order to do that we can use these below relational operators: < > <= >= But unfortunately, we can not use these below operators: == != !== === You can’t use these to compare the value of the date.

How to determine equality for two JavaScript objects?, To compare two Arraysin JavaScript, you should check that the lengthof both arrays should be the same, the objectspresented in it be the same type, and each item in one array is equivalent to the counterpart in the compared array. This tutorial will show you some ways of comparing two arrays.

We have 2 arrays in JavaScript and we want to compare one with the other to see if the elements of master array exists in keys array, and then make one new array of the same length that of the master array but containing only true and false (being true for the values that exists in keys array and false the ones that don't).

Comments
  • Ids have to be unique. Use a class instead.
  • Two elements can't have the same ID
  • Object.is(cf1[i], cf1[i++]) Two different objects are always going to be different.
  • @Keith you miss the point of an id - it is used to identify something so has to be unique, it is classed as invalid anyway if you validate your code and have duplicate ids so you really shouldn't do it - just because you can doesn't make it right
  • @Keith "id: ... There must not be multiple elements in a document that have the same id value ..." (Source)
  • Thanks, I knew there had to be at least one incredibly silly mistake in my code.
  • It seems that this only catches the first occurrence of a field with different values: if both fields are different, only the first one gets highlighted.
  • @Xhiko If you look in the console you would see the error, problem is your comparing last to previous, but your loop is going too far. I've updated the fiddle, and also got rid of the ++i's etc, as they just confuse things.
  • Thanks for the answer, but I'd rather avoid jQuery for now.