I am trying to set a custom style for elements that are
HTML:
<ul class="selector">
    <li class="selector">some li
       <ul class="">
          <li>some fancy li - the ul parent should have first class</li>
       </ul>
       <ul class="">
          <li>some more li - the ul parent should have last class</li>
       </ul>
    </li>
    <li class="selector">some second li
        <ul class="">
          <li>some lonely li - the ul parent should have first and last classes</li>
       </ul>
    </li>
</ul>
so I came up with a piece of jQuery hoping to do the trick
$('ul.selector li.selector > ul').each(function () {
  if ($(this).is(':first') && $(this).is(':last')) {
    $(this).addClass('first last');
  } else if ($(this).is(':first')) {
    $(this).addClass('first');
  } else if ($(this).is(':last')) {
    $(this).addClass('last');
  }
});
Thanks for any suggestion.
UPDATE - here is a fiddle you can play with, based on one of the answers: http://jsfiddle.net/qAtpe/
Why not just this :
$('ul.selector li.selector > ul').each(function() {
    $this = $(this); // cache $(this)
    if ($this.is(':first')) {
        $this.addClass('first'); 
    } 
    if ($this.is(':last')) {
        $this.addClass('last'); 
    }
});
Then use the following CSS
.first {
    //this is first
}
.last { 
    // this is last
}
.first.last {
    // this is first and last - ie the only child
}
$('ul.selector li.selector > ul').each(function() {
    $this = $(this); // cache $(this)
    if ($this.is(':first-child')) {
        $this.addClass('first'); 
    } 
    if ($this.is(':last-child')) {
        $this.addClass('last'); 
    }
});
Looking at your example jsfiddle - you needed the selector :first-child rather and :first ..
The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1). While this matches only a single element, :first-child can match more than one: One for each parent.
This now works :
Working example
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