Apply CSS style/class to div

10,920

Solution 1

:even and :odd are 0-indexed, and may not produce results you're looking for. The first element is number 0, and that's even, so it gets selected by :even, rather than the second one.

For 1-indexing, you're missing the :nth-child() pseudo-class:

$("div > div:nth-child(even)").addClass("evn");

Make sure that you spelled the class name correctly too, I don't know if your CSS defines an .evn class...

Solution 2

This link can help you to solve your proble

First , define the tables and div as shown below in the “index.html” file,

<table border="1">
  <tr><td>Michael</td></tr>
  <tr><td>Sam</td></tr>
  <tr><td>John</td></tr>
  <tr><td>Jason</td></tr>
</table>
 <div>Michael</div>
 <div>Sam</div>
 <div>John</div>
 <div>Jason</div>

Now, we need to write the script for displaying the different color in the alternate row,

<script src="jquery.js"></script>
<script>
$(document).ready(function()
{
  //for div
  $("div:odd").css("background-color", "#F4F4F8");
  $("div:even").css("background-color", "#EFF1F1");
  //for table row
  $("tr:even").css("background-color", "#F4F4F8");
  $("tr:odd").css("background-color", "#EFF1F1");
});
</script>

The filters “even” and “odd” can be used in jQuery for selecting odd or even index of the elements.As you can see above the background color of the odd and even “div” are changed using the “css” method and “odd” and “even” filters of jQuery and the same applies for the even and odd “tr” which means for the row of table.

Share:
10,920
Sourav
Author by

Sourav

Hi, I am Sourav Ghosh :) You can find my projects * AJAX Micro Mini Lib [JS] * Autorun Cleaner [VB.NET] * C Code Completer [VB.NET] * DockBar Develop [VB.NET] * ShoutOut-Twitter [ASP.NET + C#] * Ultra Light CAPTCHA [PHP] * Ultra Light Forum [PHP] * Wallpaper Changer [VB.NET]** @ http://sourceforge.net/users/sourav1989 I'll be really happy if you find them useful :) Thanks :)

Updated on June 15, 2022

Comments

  • Sourav
    Sourav almost 2 years

    I have some div elements
    The structure is

    <div id="comment">  
      <div id="m1">...</div>  
      <div id="m2">...</div>  
    </div>
    

    I want to apply some CSS or Class to the even/odd inner div of comments (or to the m1/m2 div)
    So i coded this, but it did not worked :(

    $("div>div:even").addClass("evn");  
    

    What i'm missing ?

  • JP Silvashy
    JP Silvashy about 13 years
    dude, links to blog posts or docs make bad answers to questions. Provide your input and help him solve his specific problem.