Avinash Avinash - 6 months ago 10
Javascript Question

Get the highest values of a data attribute

My html looks like



<div id="container">
<div class="right" data-x="1" data-y="1" ></div>
<div class="right" data-x="2" data-y="1" ></div>
<div class="right" data-x="3" data-y="1" ></div>
<div class="right" data-x="4" data-y="1" ></div>
</div>





How to get max/min value of data-x/data-y using jquery?

Answer

try this

var containerChilds = document.getElementById("container").children;
var max = 0;
for ( var counter =0; counter < containerChilds.length; counter++)
{
  var value = containerChilds[counter].getAttribute("data-x");
  if ( max < value )
  {
    max = value;
  }
}
console.log(max);

In jQuery

var max = 0;
$("#container div.right[data-x]").each(function(){
   var value = $(this).attr("data-x");
   max = max < value ? value : max;
});
console.log(max);
Comments