Set div id's from array content
Solution 1
Here is a solution for randomising class names using pure JavaScript.
Updated answer
I have updated my solution now that the question was clarified, here is it adapted to your colors. I have set the background-color
of the .card
s to the colors set in the array. This could easily be done using the id
as well, I recommend against using []
characters in an id
though as I think I'm not sure if that's standards compliant.
var colors = [
"orange","orange","pink","pink","red","red","purple","purple",
"blue","blue","green","green","brown","brown","yellow","yellow"
];
var divs = document.getElementsByClassName("card");
while (divs.length > 0) {
var i = Math.floor(Math.random() * colors.length);
divs[0].style.backgroundColor = colors[i];
colors.splice(i, 1);
divs = [].slice.call(divs, 1);
}
Original answer
Given an array of ids and a set of HTML elements, a random id
will be assigned to each element from ids
.
JavaScript
var ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var divs = document.getElementsByClassName("game-element");
while (divs.length > 0) {
var i = Math.floor(Math.random() * ids.length);
divs[0].id = 'item-' + ids[i];
ids.splice(i, 1);
divs = [].slice.call(divs, 1);
}
HTML
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
CSS
.game-element {
width:10px;
height:10px;
float:left;
}
#item-1 { background-color:#F00; }
#item-2 { background-color:#0F0; }
#item-3 { background-color:#00F; }
#item-4 { background-color:#FF0; }
#item-5 { background-color:#F0F; }
#item-6 { background-color:#0FF; }
#item-7 { background-color:#A0A; }
#item-8 { background-color:#0AA; }
#item-9 { background-color:#AA0; }
#item-10 { background-color:#000; }
Solution 2
Assign each div a randomdiv
class or something like that. That will ensure you can select on the ones you want without affecting other divs.
Then you can do this
var idArr = [/**random ids here**/];
$( ".randomdiv" ).each(function( index ) {
$(this).attr("id",idArr[index]);
});
That will loop over every div with the class randomdiv
and assign it a value from idArr
which you can define however you want, I guess with some type of randomization function for your use case
Update
With your updates to the question I'm seeing an issue. You have non unique ids that you want to set. ids must be unique. If you want to assign multiple of them to be the same you want to use classes. So the code would instead look like this
var card = ["orange","orange","pink","pink","red","red","purple","purple",
"blue","blue","green","green","brown","brown","yellow","yellow"]; $( ".randomdiv" ).each(function( index ) { $(this).addClass(card[index]); });
And then you could define the style you want with css like this
.randomdiv.blue{
background-color:blue;
}
.randomdiv.green{
background-color:green;
}
...
Solution 3
Hard to know exactly what you're after but if using jQuery you could do something like this:
HTML:
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
JavaScript:
var myarray = ["one","two","three"];
// loop through all divs
$('div.random').each(function(index) {
// set div id to array value
$('div').attr('id', myarray[index]);
});
Result:
<div class="random" id="one"></div>
<div class="random" id="two"></div>
<div class="random" id="three"></div>
Additional Comments:
Would be worth ensuring or at least checking that the array length is equal to the number of div
elements, otherwise you may receive exceptions.
Dave
Updated on March 24, 2020Comments
-
Dave about 4 years
I'm trying to figure out how to give 16 different divs the id names that are stored in a 16 elements long array.
This is so that I can randomize the divs "placement" for a memory game, since there will be 8 different div styles that will change along with the div id if that is possible.
My plan is to have the same name for the div id as for the style for that specific div.
Is there any way to set the first div's id and style as the value in myarray[0], and the second div's id and style as myarray[1], and so on?
EDIT:
var card = ["orange","orange","pink","pink","red","red","purple","purple", "blue","blue","green","green","brown","brown","yellow","yellow"]; for(var j, x, i = card.length; i; j = parseInt(Math.random() * i), x = card[--i], card[i] = card[j], card[j] = x);
then later in the body I'm trying to achieve something that represents this:
<div id="card[0]"></div> <div id="card[1]"></div> <div id="card[2]"></div>
and so on...
-
Ben McCormick about 11 yearsThis will fail if he has other divs on the page. Probably better to specify the ones he wants to randomize with a class.
-
diggersworld about 11 yearsYes it will. It's merely an example.
-
Lix about 11 yearsI can appreciate that you are trying to lend a hand here and contribute, but your answer is extremely vague. You're referencing frameworks and languages but are not actually providing a viable solution/answer to the OP's issue.
-
JJJ about 11 years1) Saying "it would be easier in another language" is not helpful at all and 2) how would templates help randomizing ids?
-
Shuping about 11 years@Lix yes I believe a code snippet will solve the problem this time but it never tells which direction actually is correct.
-
Shuping about 11 years@Juhana I did not mean do that in another language, what I mean was telling that in server side that could be easy do automatic ids assign with server side language you are using and C# is just an example.
-
Dave about 11 yearsDon't I need the unique id's to be able to see if there is a match or not?
-
Daniel Imms about 11 yearsYou can put
id
s in if you want (see my original answer), make sure they're unique though. You could compare on my updated answer against the actual styleelement.style.backgroundColor
or alternatively add a class (element.classList.add
) instead of changing the styles. -
Dave about 11 yearsI've come to a point where the game works, but since I don't really understand your code I don't know how to mix the divs once again without reloading the page. jsfiddle.net/94jerdaw/2nEqk
-
Daniel Imms about 11 yearsYou shouldn't need to change the code, throw it in a function and call it there. The function should already just overwrite the old style. jsfiddle.net/GCKNY