Is there an easy way to setup a selector with jQuery to only select the ‘last’ element if there are two or more elements? If there is only one element I would want the first selector to fire, but the first and last selector both fires. If there are two or more elements then everything behaves as expected. I have a work around right now where I just check to see how many elements exist and then setup the other code, but I’m thinking there has to be a better way.
jQuery stuff
$('div#firstDiv span:first').click(function(e) {
alert('first span clicked');
});
$('div#firstDiv span:last').click(function(e) {
alert('last span clicked');
});
$('div#secondDiv span:first').click(function(e) {
alert('first span clicked');
});
$('div#secondDiv span:last').click(function(e) {
alert('last span clicked');
});
html stuff
<div id="firstDiv">
<span>Only Span</span>
</div>
<br />
<div id="secondDiv">
<span>First Span</span>
<br />
<span>Second Span</span>
</div>
jsfiddle link for a live demo -> http://jsfiddle.net/dXPKz/
Change your
:lastrules to also be:not(:first). This way they will only fire if there are more than 1 elements found.