Reputation: 13
My example:
<div id="main">
<div class="here" id="dsf">a</div>
<div class="no" id="sdf">b</div>
<div class="here" id="sdfsdf">c</div>
<div class="here" id="dssdf">d</div>
<div class="no" id="ds3f">e</div>
<div class="here" id="ds4f">f7</div>
<div class="no" id="tert4">b8</div>
<div class="no" id="r4tt4">5c</div>
<div class="here" id="ert4">d4</div>
<div class="no" id="fdgd4">e3</div>
<div class="here" id="fghf3">2f</div>
</div>
var rand = Math.floor((Math.random() * 10) + 1);
if(rand > 5){
var here = $('div div.here');
} else {
var here = $('div div.no');
}
console.log(here);
How can I get the first and last elements from "here"? I would like get the ID of these elements.
FIDDLE: http://jsfiddle.net/5BfPL/2/
Upvotes: 1
Views: 71
Reputation: 3106
You can do it using jQuerys.first()
and .last()
.
.first()
: Reduce the set of matched elements to the final one in the set.
.last()
: Reduce the set of matched elements to the first in the set.
With those to you can select retrieve the element. Than you can just use .prop()
or .attr()
(depending on your jQuery version) to get the id
.
Example::
var firstElement = $('div div.here').first().prop('id');
var lastElement = $('div div.here').last().prop('id');
As per your request in the comment, you can get the 3th element using the .eq()
.eq()
: Reduce the set of matched elements to the one at the specified index.
Example:
var thirdElement= $('div div.here').eq(2); // the parameter is 0-based.
Upvotes: 3