Reputation: 65
I'm finding way how to comparing value on <div>
on other div tag that has same class name. So, I'm thingking to do it in jquery. Below is example of <div>
tag that I want to compare ;
<div class="helloword" value="4"> </div>
<div class="helloword" value="3"> </div>
<div class="helloword" value="2"> </div>
<div class="helloword" value="1"> </div>
I want to make comparasion which which one classes that has smallest value. So it's that possible to do?
Upvotes: 0
Views: 1217
Reputation: 14669
function GetSmallestValue(itemValue)
{
$(".helloword").each(function (a, b) {
var newValue = $(this).attr("value");
if (itemValue==0 || newValue < itemValue) {
itemValue = newValue;
}
});
return itemValue;
}
var itemValue = GetSmallestValue(0);
console.log(itemValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="helloword" value="4"> </div>
<div class="helloword" value="3"> </div>
<div class="helloword" value="2"> </div>
<div class="helloword" value="1"> </div>
Upvotes: 1
Reputation: 61794
You need to select all the divs by their class, then loop through them and maintain a pointer to the lowest one you've found so far:
var lowestVal = 100; //set this higher than your max value
var divs = $(".helloword"); //select all the elements by their class
//loop through each item and compare it to the lowest recorded one
divs.each(function(index, element) {
var val = parseInt($(element).attr("value"));
if (val < lowestVal) lowestVal = val;
});
Now you can use lowestVal for whatever you need.
Upvotes: 1
Reputation: 122027
You can use map()
and Math.min.apply()
to get min value.
var min = Math.min.apply(null, $('.helloword').map(function() {
return parseInt($(this).attr('value'))
}))
console.log(min)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="helloword" value="4"></div>
<div class="helloword" value="3"></div>
<div class="helloword" value="2"></div>
<div class="helloword" value="1"></div>
Upvotes: 2
Reputation: 594
Get all divs using class selector and loop through them using .each() , an untested code as bellow:
var min = 10, minElement = '';
$('.helloword').each(function(){
var value = parseInt($(this).attr("value"));
if (value < min) {
min = value;
minElement = $(this);
}
});
// using minElement
Upvotes: 1