I want to only select elements that match class X and don't have any siblings that also have class X. In my case, X = hasDatepicker
. Here's what I've come up with:
$('.hasDatepicker:not(.hasDatepicker ~ .hasDatepicker)')
However, this does not exclude the first element, so in any group of datepickers, this will still select the first one. I don't want to include any that are in a group, only the singles.
Example with 1 Match:
<div class="input text">
<input name="data[Goal][date_started]" type="text" value="" class="hasDatepicker" style="display: none; ">
<button type="button" class="ui-datepicker-trigger"><img src="/themed/mocha/images/btn_calendar.png" alt="..." title="..."></button>
</div>
Example with 0 Matches:
<div class="input text">
<input type="text" value="" id="GoalDateStarted" class="hasDatepicker"><input type="text" value="" class="hasDatepicker" style="display: none; ">
<input type="text" value="" class="hasDatepicker" style="display: none; ">
<input name="data[Goal][date_started]" type="text" value="" class="hasDatepicker" style="display: none; ">
<button type="button" class="ui-datepicker-trigger"><img src="/themed/mocha/images/btn_calendar.png" alt="..." title="..."></button>
</div>
Any ideas? Thanks!
It is not that elegant but it does the trick using the :first-child pseudo-selector and filtering the result set with .filter():
:first-child
will help select only the first .test element of a possible multiple siblings list
use .filter()
to actually check if there are no siblings with the same class
Here's the code:
var a = $('.test:first-child').filter(function() {
//return $(this).parent().find('.test').not(this).length == 0;
return !$(this).siblings('.test').length
});
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With