Reputation: 317
Im trying to display a grid of divs with individual IDs.
I found that when the width value exceeds 10, the grid starts to create some weird patterns, some lines extend beyond the width value, some lines fold too quickly.
When I create the cell ID using
cellId = x.toString() + "/" + y.toString();
everything seems to be ok.
What does that
+ "/" +
change? Other than simply adding string to the cellId?
I post entire code, 1) because it's short 2) to make sure the problem is not within the css.
<head>
<style type = "text/css">
.pixel {
font-size:12px;
font-family: sans-serif;
float:left;
width:20px;
height:20px;
}
</style>
<script type = "text/javascript">
</script>
</head>
<body>
<script type="text/javascript">
function drawBoard(height, width) {
for (x=0; x<=height; x++) {
for (y=0; y<=width; y++) {
cell = document.createElement('div');
// cellId = x.toString() + "/" + y.toString();
cellId = x.toString() + y.toString();
cell.setAttribute("id", cellId);
document.body.appendChild(cell);
document.getElementById(cellId).setAttribute("class", "pixel");
if (y == 0) {
document.getElementById(cellId).style.clear = "both";
console.log(y);
}
document.getElementById(cellId).innerHTML = cellId;
}
}
}
drawBoard(18, 10);
</script>
</body>
Upvotes: 0
Views: 44
Reputation: 413936
Your id values consist of two numbers glued together. When x
is 8 and y
is 32, you end up with 832. But also, when x
is 83 and y
is 2, you also end up with 832.
Your code is creating elements with duplicate id values, and that's the heart of the problem. Using the "/" character in the middle solves it. Now, in that case described above, you'd get "8/32" and "83/2".
You could use any other character besides "/" of course.
Upvotes: 6