Find the highest value ending ID

Asked

Viewed 302 times

2

I have an html structure like this:

<div id="container1">
    <p>Texto</p>
</div>
<div id="container2">
    <p>Texto</p>
</div> N vezes este bloco
<div id="containerN">
    <p>Texto</p>
</div>

I wonder how I get the last one id="containerN", separate the number that equals the N and put into a variable. For example, if the latter is the ID="container22" I want to put in the variable cont=22.

3 answers

2

You can use jQuery to select all Ivs whose ID starts with "container", then sort them (if DOM is not already in the right order) and then fetch the last of that array.

If I understand the question you want in a variable cont the number on the ID. You can do something like this:

var cont = $('[id^="container"]').get().map(function (div) {
    var nr = div.id.match(/(\d+)/);
    return parseInt(nr[1], 10);
}).sort(function (a, b) {
    return a - b
}).pop();

console.log(cont); // 22

jsFiddle: https://jsfiddle.net/42qj4217/

2


To simplify you could instead of using the ID to make the selection use CLASS and the desired data in the ID, the structure would look like this:

<div id="1" class="container">
    <p>Texto</p>
</div>
<div id="2" class="container">
    <p>Texto</p>
</div> N vezes este bloco
<div id="3" class="container">
    <p>Texto</p>
</div>

And your selection would look like this:

var cont = $('.container').last().attr('id');
  • $('.container').last() does not guarantee that the largest number will return, in case the DOM is mixed. (Still +1 by the idea, which could also be data-id instead of ID.)

  • 1

    Correct @Sergio, I assumed that the Divs would be in order, data-id is also a good.

0

You can do it this way (without jQuery):

var divs = document.getElementsByTagName("div");
var length = divs.length;
var highest = 0;
for(var i = 0; i < length; i++) {
    var id= parseInt(divs[i].id.substring(9, divs[i].id.length), 10);
    if(id > highest) {
        highest = id;
    }
}
alert(highest);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.