Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i select only last span element in a div ? it should not select if only one span in the div

I have HTML like this

$('.elementContainers').find('.labelText:last:not(".labelText:first")').css('margin-left','150px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="elementContainers">
<span class="labelText mandatory" >First Name</span>
<span class="spacing"></span>
<input type="text" class="customInput" id="firstName"  name="firstName" value="" pattern="[A-Za-z]{2,}" required/>

<span class="labelText" >Last Name</span>
<span class="spacing"></span>
<input type="text" class="customInput" id="lastName" value=""  name="lastName"  pattern="[A-Za-z]{1,}" required/>
</div>
<div class="elementContainers">
<span class="labelText mandatory"  >Gender</span>
<span class="spacing"></span>
<input type="radio" name="gender"  >Male 
<input type="radio" name="gender" >Female
</div>

I want to select last labelText in every elementContainer

$('.elementContainers').find('.labelText:last')

This gives me exactly what i need,but i need to check that first and last should not be the same(elementContainer should contain two elements )

How can i check that with :not selector or any other selector.

I have tried something like this

$('.elementContainers').find('.labelText:last:not(".labelText:first")')

But its not working,its returning no elements.

Thanks :)

like image 561
Jayababu Avatar asked Jan 07 '23 08:01

Jayababu


1 Answers

If you want to select the last span in a div, but only where there is more than one span in the div, then the following selector should work.

$('div').find('span:gt(0):last').addClass('selected');

It's finding any span's at an index > 0 (https://api.jquery.com/gt-selector/), and then getting the last of those.

http://jsfiddle.net/daveSalomon/vnorunwm/

Your code could look something like this....

$('.elementContainers').find('.labelText:gt(0):last').css('margin-left','150px');

http://jsfiddle.net/daveSalomon/qoebk8j9/

like image 200
Dave Salomon Avatar answered Jan 09 '23 22:01

Dave Salomon