Get the last visible div attribute

It is hard to explain. Here is 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 basically need to find the last one <div>in container <div>and get the attribute from it row. This 99% of the time is the highest number, but not guaranteed.

+5
source share
2 answers

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

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

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

You can consider the HTML5 attribute data-for custom attributes. jQuery supports it in older browsers using 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');

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

+6

jQuery :

$('div#container > div').last().attr('row')
+3

All Articles