Sourav
Sourav

Reputation: 17530

Apply CSS style/class to div

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 ?

Upvotes: 2

Views: 10946

Answers (2)

Amit
Amit

Reputation: 22076

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.

Upvotes: 1

BoltClock
BoltClock

Reputation: 723638

: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...

Upvotes: 4

Related Questions