Discover the highest-valued endpoint ID

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 would like to know how I can get the last id="containerN" , separate the number that equals N and put it in a variable. For example, if the last one is ID="container22" I want to put it in the cont=22 variable.

    
asked by anonymous 01.04.2015 / 20:20

3 answers

2

For simplicity 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');
    
01.04.2015 / 20:50
2

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

If I understood correctly the question you want in a variable cont the number that is in 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: link

    
01.04.2015 / 20:34
0

You can do this (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);
    
26.05.2017 / 20:50