February 27, 2013

How to add style for every first list element, first children with jQuery

Question by djlukas777

I have this markup:

<ul>
  <li> // this
    <ul>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
    </ul>
  </li>
  <li> // this
    <ul>
      <li>
        <div></div>
      </li>
      <li>
        <div></div>
      </li>
    </ul>
  </li>
</ul>

In my style i have this:

.main_menu ul > li {
   // some style
}

and that gives me some style for only first li in that tree, not for children li of it.
So, my question is how to set this with jQuery, when i’m trying with $('.main_menu ul > li'); it doesn’t work. I guess i need some kind of this write:

$('.main_menu ul').each().first().child();

but it’s not correctly, can you help me?

Answer by Starx

Pseudo selector called :first-child can select the first child of a element. This is a CSS selector and jQuery also supports it. So you can use it either by CSS or jQuery.

ul li:first-child {
   /* Your style */
}

or jQuery

$("ul li:first-child").css('style-name', 'property value');

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!