I have the following divs:
test
test
You can use the sort function to do it.
function arrayify(obj){
return [].slice.call(null,obj);
}
var all = arrayify(document.querySelectorAll('div[id]'));
var max = all.sort().pop();
var min = all.sort().reverse().pop();
This is way easier that using jQuery
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;
}
});
You should use data instead of id for this.
<div data-value="2" class="maindiv">test</div>
<div data-value="5" class="maindiv">test</div>
<div data-value="3" class="maindiv">test</div>
etc.
Edit: I shortened my answer in favour of Rory McCrossan's accepted answer above.
var valArray = [];
$('.maindiv').each(function(){
valArray.push(parseInt($(this).attr('id'), 10));
})
valArray.sort(function(a, b) { return a - b })
valArrayp[0] // lowest
valArrayp[valArrayp.length - 1] // highest`
Have not tested, should work though
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/
First you need to create an array containing all the id
values, then use Math
to get the highest/lowest:
var ids = $(".maindiv[id]").map(function() {
return parseInt(this.id, 10);
}).get();
var highest = Math.max.apply(Math, ids);
var lowest = Math.min.apply(Math, ids);
Example fiddle
Note the [id]
attribute selector is required, otherwise 0
is assumed for the missing value.