I have the following divs:
<div id="2" class="maindiv">test</div>
<div id="5" class="maindiv">test</div>
<div id="3" class="maindiv">test</div>
<div id="1" class="maindiv">test</div>
<div class="maindiv">test</div>
<div id="4" class="maindiv">test</div>
How to get the highest id (5) and the lowest id (1) in jQuery or Javascript?
To achieve this you can create an array containing all the id
values, then use Math
to get the highest/lowest:
var ids = $('.maindiv[id]').map((i, el) => parseInt(el.id, 10)).get();
var lowest = Math.min.apply(Math, ids); // = 1
var highest = Math.max.apply(Math, ids); // = 5
console.log(`${lowest} => ${highest}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="2" class="maindiv">test</div>
<div id="5" class="maindiv">test</div>
<div id="3" class="maindiv">test</div>
<div id="1" class="maindiv">test</div>
<div class="maindiv">test</div>
<div id="4" class="maindiv">test</div>
Note the [id]
attribute selector is required, otherwise 0
is assumed for the missing value.
If you need IE support, you need to use an anonymous function instead of the arrow function:
var ids = $(".maindiv[id]").map(function() {
return parseInt(this.id, 10);
}).get();
function minMaxId(selector) {
var min=null, max=null;
$(selector).each(function() {
var id = parseInt(this.id, 10);
if ((min===null) || (id < min)) { min = id; }
if ((max===null) || (id > max)) { max = id; }
});
return {min:min, max:max};
}
minMaxId('div'); // => {min:1, max:5}
http://jsfiddle.net/qQvVQ/
var min = Number.MAX_VALUE, max = Number.MIN_VALUE;
$(".maindiv").each(function () {
var id = parseInt(this.id, 10);
if (id > max) {
max = id;
}
if (id < min) {
min = id;
}
});
Create a global variable and compare it to each element using Math.max
inside a loop.
var maxval = Number.MIN_VALUE,
minval = Number.MAX_VALUE;
$('div').each(function () {
var num = parseInt(this.id, 10) || 0; // always use a radix
maxval = Math.max(num, maxval);
minval = Math.min(num, minval);
});
console.log('max=' + maxval);
console.log('min=' + minval);
http://jsfiddle.net/mblase75/gCADe/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With