Get the highest and lowest values of a certain attribute in jQuery or Javascript
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/
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();