I have a range of divs, each with an incremental ID:
<div id="1">contents</div>
<div id="2">contents</div>
<div id="3">contents</div>
<div id="4">contents</div>
<div id="5">contents</div>
<div id="6">contents</div>
...
I'm trying to assign a class through JQuery by selecting by ID: $('#id').addClass('someClass');
but I want the '#id' to be selected randomly from the range I have there. The range could be sizable, maybe up to 50 ids or more. I'm guessing this will have to read the IDs as number, right?
How do I get a random number there?
...Here's the full scheme:
setInterval ( "flipit()", 3000 );
function flipit ( ) {
$(document).ready(function(){
var elmId = 'nS_' + (Math.floor(Math.random() * 6) + 1);
$('#' + elmId).addClass('numSen2');
});
}
<style type="text/css">
.numSen {
visibility: hidden;
}
.numSen2 {
visibility: visible;
}
</style>
<div class="numSen" id="nS_1">contents</div>
<div class="numSen" id="nS_2">contents</div>
<div class="numSen" id="nS_3">contents</div>
<div class="numSen" id="nS_4">contents</div>
<div class="numSen" id="nS_5">contents</div>
<div class="numSen" id="nS_6">contents</div>
Use
Math.floor
in combination withMath.random()
to create a random selector:I would re-work your elements so they have some class ahead of time. This way, you can select an element from those that you want to change, rather than everything.
And then in your JavaScript:
Untested, but should work, or be close to it.
You can do it even shorter. This will select a
div
with randomid
between 1-100 andhide()
it:Edit:
'#id'
is just a string. So, after fixing your IDs (they must start with a letter), build a string like you would anywhere else: