Get the highest and lowest values of a certain attribute in jQuery or Javascript

前端 未结 7 1111
鱼传尺愫
鱼传尺愫 2020-12-10 05:37

I have the following divs:

test
test
7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 06:19

    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.

提交回复
热议问题