How to create div using for loop in javascript
Hey, I'm trying to create multiple div elements using a for loop in JavaScript. Here's the code snippet I have so far:
<script> for (let i = 0; i < 5; i++) { const div = document.createElement('div'); div.textContent = `This is div ${i + 1}`; document.body.appendChild(div); } </script>
The problem is that while this code does create div elements, they all stack on top of each other. I want them to appear side by side. Can anyone help me with this?
save
listen
AI Answer
How to create div using for loop in javascript
7
Hey, I'm trying to create multiple div elements using a for loop in JavaScript. Here&…
asked
Apu
7 answers
2915
Hey, I'm trying to create multiple div elements using a for loop in JavaScript. Here&…
Answer Link
answered
Apu
for (let i = 0; i < 5; i++) {
const div = document.createElement('div');
div.textContent = `This is div ${i + 1}`;
div.style.display = 'inline-block';
document.body.appendChild(div);
}
</script>This should make your divs appear side by side.
container.style.textAlign = 'center';
for (let i = 0; i < 5; i++) {
const div = document.createElement('div');
div.textContent = `This is div ${i + 1}`;
div.style.display = 'inline-block';
div.style.marginRight = '10px';
container.appendChild(div);
}
document.body.appendChild(container);This should center your divs on the page horizontally.
container.style.textAlign = 'center';
for (let i = 0; i < 5; i++) {
const div = document.createElement('div');
div.textContent = `This is div ${i + 1}`;
div.style.display = 'inline-block';
div.style.marginRight = '10px';
div.style.backgroundColor = getRandomColor();
container.appendChild(div);
}
document.body.appendChild(container);
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}This should give each div a random background color.