Q:

Add class randomly to only one of two divs

I have two divs and I want to add the class ".active" to only one of them at random.
This is the best I could come up with, however, sometimes both divs get the class added.
randomClass: function(){
        var classes = ["active", ""];
         $(".contain > div").each(function(){
           $(this).addClass(classes[~~(Math.random()*classes.length)]);
        });
    },

HTML
 <div class="contain">
    <div></div>
    <div></div>
 </div>

A:

I wrote the following code to use the eq.  It will select a random number between the valid indexes and then return that value and then append the proper class.  I added one line to remove whichever one currently has the class active, so the button would work.
Important logic error with your code: by using .each you are not guaranteeing that both or none are not selected.  You have to select the object before hand.
With your code, here is the possible out comes (where 1 is active and 0 is not active):
1 0
0 1
1 1
0 0

There is a 50% chance your code will not work as intended.
So, I wrote mine a little differently.

function randomClass(){
 $(".contain > div").removeClass("active");
 $(".contain > div").eq(Math.floor(Math.random()*$(".contain > div").length)).addClass("active");
}


randomClass();
.active {
 background-color:red;
}
.box {
 width:50px;
 height:50px;
 border:1px solid black;
 margin:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contain">
 <div class="box"></div>
 <div class="box"></div>
</div>

<button onclick="randomClass()">New Random</button>

