Crag
Crag

Reputation: 458

jQuery first and last selectors with one/two elements

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/

Upvotes: 0

Views: 236

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Change your :last rules to also be :not(:first). This way they will only fire if there are more than 1 elements found.

$('div#firstDiv span:last:not(:first)').click(function(e) {
    alert('last span clicked');
}); 

Upvotes: 1

ar3
ar3

Reputation: 4063

I'm not sure if you can do this in one selector, but you could add a filter and utilize the :not selector...as seen here (jsFiddle)...it would be cool to do this in one selector though...

Upvotes: 1

Related Questions