Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why .first() won't work here?

Tags:

jquery

In the following code, I'm trying to get the value of the first div under "latest", but I keep getting "undefined". I'm expecting the value 5705. This should have worked, right? How do I set this right?

var auto_refresh = setInterval(function()
{
    console.log($('.latest').first().attr('lastValue'));
}, 5000); // refresh every 5 seconds

The html part: There'll be more divs added here. So 5705 may be 5710 or something else.

<div class="latest">
<div class="story" lastValue="5705">Story 5</div>
<div class="story" lastValue="5704">Story 4</div>
<div class="story" lastValue="5703">Story 3</div>
<div class="story" lastValue="5702">Story 2</div>
<div class="story" lastValue="5701">Story 1</div>
</div>
like image 213
Norman Avatar asked Nov 06 '12 08:11

Norman


3 Answers

you have to select the first child and not the first container

$('.latest>div').first().attr('lastValue')

or

$('.latest').children().first().attr('lastValue')
like image 144
amd Avatar answered Nov 08 '22 02:11

amd


You want to select first child, not first element with class latest.

console.log($('.latest > div').first().attr('lastValue'));
like image 34
Michal Klouda Avatar answered Nov 08 '22 01:11

Michal Klouda


Because you're selecting the wrong element(s), you want the .story elements, but you're selecting the .latest elements. Use:

$('.latest .story:first').attr('lastValue');

Or:

$('.latest .story:first-child`).attr('lastValue');

Or:

$('.story:first-child').attr('lastValue');
like image 2
David Thomas Avatar answered Nov 08 '22 03:11

David Thomas