Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  142] [ 7]  / answers: 1 / hits: 34227  / 11 Years ago, sun, december 1, 2013, 12:00:00

I am new to JavaScript and would like to know how I can create multiple divs dynamically with the same class name. I have the following code but it only creates one instance of the div.



<div id=wrapper>
<div id=container>
<div id=board>
<script>
var board = document.createElement('div');
board.className = blah;

for(x=0; x<9;x++) {
document.getElementById('board').appendChild(board);
}
</script>
</div>
</div>
</div>

More From » javascript

 Answers
43

Right now, you're creating the element outside the loop, and appending that element to the DOM...again and again.



What you want to do is create a new element during every iteration of the loop. To do that, move the part where you create the new div inside the loop:



for(x=0; x<9;x++) {
var board = document.createElement('div');
board.className = blah;

document.getElementById('board').appendChild(board);
}


Now, every time the loop runs, you'll create a new element, and append that element to the element with ID #board.



It's worth pointing out that the variable you created (board) now only has scope within this loop. That means that once the loop is done, you'll need to find a different way to access the new elements, if you need to modify them.


[#73969] Friday, November 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aubriea

Total Points: 641
Total Questions: 118
Total Answers: 101

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;