I've a bunch of divs with each div id starting with a common name and ending wiht a incremental number:
<div id="thisismydiv1"></div>
<div id="thisismydiv2"></div>
<div id="thisismydiv3"></div>
开发者_开发知识库<div id="thisismydiv4"></div>
How do I find out the latest number i.e. 4 using jQuery?
var token = "thisismydiv";
var id = $('div[id^="' + token + '"]').last().id;
id = id.replace(token, '');
alert(id);
Demo: jsFiddle
$("div").last().attr('id');
or
$("div:last").attr('id');
.last()
or :last
will do it
I think the last selector may help you - http://api.jquery.com/last-selector/
$('div:last');
Use the [^=]
selector to find the elements where the id starts with that string, get the numeric part of the id, parse it, and check for the highest value:
var highest = 0;
$('[id^="thisismydiv"]').each(function(){
var id = parseInt(this.id.substr(11));
if (id > highest) highest = id;
});
alert(highest);
Demo: http://jsfiddle.net/Guffa/cdQ9C/
If the parent container only has these divs and your ids start at one and increment by one, you could just get the children count of the parent.
$("parent").children().length;
If not, you can use the last
selector like others have mentioned.
$('div[id^="thisismydiv"]').last().attr('id').match(/\d+/);
Will return 4.
Demo: http://jsfiddle.net/rSSG8/
精彩评论