I have something like this:
<div id="row1">Some content</div>
<div id="row2">Some content</div>
<div id="row3">Some content</div>
<div id="row4">Some content</div>
<div id="row7">Some content</div>
<div id="row15">Some content</div>
<div id="row915">Some content</div>
<div id="row919">Some content</div>
Rows are actually pulled from PHP array and now I need to extract last row's number e.g. in this case that would be 919. (so I can add +1 to row id when I use append to generate more rows via jQuery).... Any ideas ?
I have something like this:
<div id="row1">Some content</div>
<div id="row2">Some content</div>
<div id="row3">Some content</div>
<div id="row4">Some content</div>
<div id="row7">Some content</div>
<div id="row15">Some content</div>
<div id="row915">Some content</div>
<div id="row919">Some content</div>
Rows are actually pulled from PHP array and now I need to extract last row's number e.g. in this case that would be 919. (so I can add +1 to row id when I use append to generate more rows via jQuery).... Any ideas ?
Share Improve this question asked Dec 19, 2012 at 8:15 PeterPeter 1,2965 gold badges20 silver badges41 bronze badges 1-
parseInt(this.id.replace('row',''),10) +1
– adeneo Commented Dec 19, 2012 at 8:19
5 Answers
Reset to default 5Id suggest rather than doing this you keep a variable with the last value. When you then append you can alter this value. This saves getting the id and parsing it.
assuming they're in the same div, and assuming that the row919 is the last element, you can do something like this:
var last_element_id = $('.parentDiv').last().attr('id');
var number = last_element_id.replace('row','');
If you cant do what Jon have suggested you can try this:
var max = -Infinity;
$('div').each(function () {
var match = this.id.match(/^row([0-9]+)$/)
if (max < match[1]) {
max = match[1];
}
});
$('#row' + max).html('Max!');
Here is an example fiddle: http://jsfiddle/HTkkb/
The script above finds the maximum number for postfix of all div's ids and gets the element with id row + max
Use :last
alert($('div:last').attr('id').split('row')[1]);
Fiddle example jsfiddle
It easier to use the data-
attribute and a class:
<div class="row" data-id="1">Some content</div>
<div class="row" data-id="2">Some content</div>
As the other answers have said, storing a variable and incrementing would be better to get the next increment. However you should still consider the data-id structure and not trying to parse it out of the id attribute which has a label wihthin it.