Zim3r
Zim3r

Reputation: 608

change color of odd/even DIVs in html using javascript

For example we 5 DIVs:

<div id="container" >
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="child">5</div>
</div>

How can I change the background color of even DIVs?

Upvotes: 6

Views: 8839

Answers (5)

mplungjan
mplungjan

Reputation: 178126

CSS3 - not working in older browsers such as IE8

#container2 > div:nth-child(even){
  background: yellow;
}

jQuery which does work in IE8 too

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

I also found this discussion: IE8 and jQuery selectors

Here is a DEMO of CSS3 and jQuery both

$("#container1 > div:nth-child(even)").addClass("even");
.even {
  background-color: yellow
}

#container2>div:nth-child(even) {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
jQuery:
<div id="container1">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="child">5</div>
</div>
<hr/> CSS3:
<div id="container2">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="child">5</div>
</div>

Upvotes: 10

Matthew Whittemore
Matthew Whittemore

Reputation: 475

If you wanted a javascript option for some reason (maybe you're looking to do more than just a class?) you could use the each() function in jquery. Here is a functioning example to boot!

CSS

.redBox{
    background-color: #ff0000;
}​

Javascript

var i = 0;
$(".child").each(function(i){
    if(i%2===0){
        $(this).addClass("redBox");
    }
    i++;
});

Upvotes: 7

manman
manman

Reputation: 5113

You can also use CSS3 nth-child selector. You can find samples on Here

Upvotes: 2

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

try nth-child demo

div:nth-child(even){
background: yellow;
}

div{
 background: red;
}

Upvotes: 6

Marc
Marc

Reputation: 6771

Just do it with CSS?

#container child:nth-child(even) {background: #CCC}

Upvotes: 2

Related Questions