icecub icecub - 7 months ago 20
Javascript Question

Content generated with Javascript ignores CSS classes?

I'm working on a simple memory game generated by Javascript. The idea is to create 24 buttons in 4 rows with 6 buttons each. To do this, I'm using the following code:

function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}

var buttons = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];

function playGame(){
shuffle(buttons);

for(i = 0; i < buttons.length; i++){
document.write("<a href='#' class='btn_Numbers'>" + buttons[i] + "</a>");
if(i == 5 || i == 11 || i == 17 || i == 23){
document.write('<br />');
}
}
}


This works perfectly fine, except that the generated hyperlinks completely ignore the CSS class
btn_Numbers
. When I write such a hyperlink manually, it works perfectly.

I have a feeling that this is caused because the CSS was loaded before the content exists. I vaguely remember something like this happened to me before a few years ago. But I really can't remember how to fix the problem. So any help would be appreciated!

Answer

No, that's not the case. Using document.write removes everything else on your page (including your stylesheets) so while it doesn't look like your CSS gets applied, it's because there is no CSS because calling document.write removed it.