3

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

3
  • 2
    Can you please illustrate that with a code sample ? Commented Mar 23, 2013 at 13:44
  • It shouldn't be too difficult to do this using a loop structure. Have you tried to implement anything already? Commented Mar 23, 2013 at 13:48
  • your ids that you want to set are not unique. You're going to want classes instead. See the updates to my answer Commented Mar 23, 2013 at 13:58

4 Answers 4

7

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

jsFiddle

enter image description here

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.

jsFiddle

enter image description here

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; }
Sign up to request clarification or add additional context in comments.

4 Comments

Don't I need the unique id's to be able to see if there is a match or not?
You can put ids in if you want (see my original answer), make sure they're unique though. You could compare on my updated answer against the actual style element.style.backgroundColor or alternatively add a class (element.classList.add) instead of changing the styles.
I'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
You 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
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;
}
...

Comments

1

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.

2 Comments

This will fail if he has other divs on the page. Probably better to specify the ones he wants to randomize with a class.
Yes it will. It's merely an example.
-1

Your page could be either rendered in server side or client side

1) in server side, that is much more easier with your server side language (e.g. C#) and framework (e.g. ASP.NET)

2) in client side, you could generate your DOM based on any JavaScript template (e.g. underscore template) and render it by passing the array as data model) you may refer to underscore template method: http://underscorejs.org/#template

EDIT

for an example on server side (I use C# and MVC razor view as example, but it could be the same idea if you use any other language and web server).

@{ ids = ... }
@foreach (var id in ids) 
{
  <div id="@id"></div>
}

the code will help you to generate the div with ids you defined.

and on client side (I use underscore template, but again same idea if you use any other engine)

var list = "_.each(ids, function(id) {<div id='<%id%>'></div>});";
_.template(list, {ids: ['id1', 'id2', 'id3']});

this will generate 3 div with the ids listed.

Update

It's better to generate the id when generating the div rather than firstly generate the div then modify its id.

4 Comments

I 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.
1) Saying "it would be easier in another language" is not helpful at all and 2) how would templates help randomizing ids?
@Lix yes I believe a code snippet will solve the problem this time but it never tells which direction actually is correct.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.