Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to check if child is first and also last

I am trying to set a custom style for elements that are

  • ul - the first in many children (ul.first)
  • last in many children (ul.last)
  • the only child (ul.first.last or ul.only)

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/

like image 755
thednp Avatar asked Dec 15 '22 21:12

thednp


1 Answers

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
}

Update

$('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

like image 121
Manse Avatar answered Jan 26 '23 01:01

Manse