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

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

I have the following divs:

test
test
相关标签:
7条回答
  • 2020-12-10 05:55

    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

    0 讨论(0)
  • 2020-12-10 05:59
    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;
        }
    });
    
    0 讨论(0)
  • 2020-12-10 06:04

    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.

    0 讨论(0)
  • 2020-12-10 06:04
    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

    0 讨论(0)
  • 2020-12-10 06:18
    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/

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题