I have a series of objects that have an attribute of
data-b='[0-9]', and I'm using jQuery to determine what the last value in the list is, up to that point. Here's what I have:
<div data-b="0">
<div></div>
</div>
<div data-b="1">
<div></div>
</div>
<div data-b="2">
<div></div>
</div>
<script>
var lB = $('div').last().data('b');
alert(lB);
</script>
Here's the craziness: as it's written above, I get an alert of "undefined". But if I take out the empty child
<div></div>, it alerts with the number 2, as expected.
I also tried using
$('div').last().attr('data-b');, but had the same result.
This Javascript (not jQuery) DID work. I haven't benchmarked it, though, and I think it will be about 1 million times slower than last():
var lB = 0;
for (var i=0; i < document.getElementsByTagName('div').length; i++) {
var el = document.getElementsByTagName('div')[i];
if (el.getAttribute('data-b'))
lB = el.getAttribute('data-b');
}
alert(lB);
My third thought is to modify each
<div data-b='[0-9]'></div> to include
<script>lB++</script> after it. But that would require a manual modification to every page, so I'm thinking of that as a last resort.
Can you guys suggest a better way of getting this value?