Get the highest id

PLease, someone will give me a solution for this. Problem in I generate dynamic identifiers dynamically on an html page using jquery. I want to find the largest identifier if the identifiers are specified, for example: ID0, ID1, ID2 .......... PLease, someone will give me a solution. Thank you for reading.

+3
source share
3 answers

a working example of the following code can be found at http://www.jsfiddle.net/LdgN9/2/

// create an array
var ar = new Array();
// for each element with id that starts with 'id'
$('[id^="id"]').each(
     function(){
                // add it to the array (only its numeric part)
                ar.push(
                        // extract the numeric part to be added in the array
                        parseInt( $(this).attr('id').replace('id','') )
                      );
               });
// find the max value in the array 
alert('id' + Math.max.apply( Math, ar ));
+5
source

If you do not add elements to the page so that they are in the DOM order, you can find it like this:

function withMaxId() {
  var max = -1, maxe = null;
  $('[id^=id').each(function() {
    var idv = parseInt(this.id.replace(/^id/, ''), 10);
    if (idv > max) {
      max = idv;
      maxe = this;
    }
  });
  return maxe; // change to just "max" if you only want the id value
} 

Of course, if you know more about the elements, you can replace $('*')it with something more selective.

+1

Try:

alert($('element[id^="id"]:last').attr('id'));

Note: Since you did not specify, I assume that the order of the elements increases in the DOM.

-1
source

Source: https://habr.com/ru/post/1751978/


All Articles