Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last visible div's attribute

Tags:

html

jquery

This is kind of hard to explain. Here's an example of my HTML:

<div id="container">
    <div row="1">
    </div>
    <div row="2">
    </div>
    <div row="3">
    </div>
    <div row="4">
    </div>
    <div row="5">
    </div>
</div>

I need to basically find the last <div> in the container <div> and get the row attribute from it. This 99% of the time ends up being the biggest number, but not guaranteed to be.

like image 202
slandau Avatar asked May 15 '11 00:05

slandau


2 Answers

Use the last-child-selector[docs] to fetch the last row, then the attr()[docs] method to get the value of the attribute.

var row = $('#container > div:last-child').attr('row');

Example: http://jsfiddle.net/TZyPT/

You may want to consider the HTML5 data- attribute for custom attributes. jQuery supports it in older browsers with the data()[docs] method.

<div id="container">
    <div data-row="1">
    </div>
    <div data-row="2">
    </div>
    <div data-row="3">
    </div>
    <div data-row="4">
    </div>
    <div data-row="5">
    </div>
</div>

var row = $('#container > div:last-child').data('row');

Example: http://jsfiddle.net/TZyPT/1/

like image 123
user113716 Avatar answered Oct 13 '22 08:10

user113716


jQuery has a lovely method for that:

$('div#container > div').last().attr('row')
like image 32
omninonsense Avatar answered Oct 13 '22 07:10

omninonsense