Reputation: 15
I'm very new to HTML and javascript but I need to create a grid container of buttons in which the text displayed on the button is an element in a list. in other words, I need each button's text to be different from one another. I was thinking to use a for loop but I'm not sure that's the way to go. I started with making the text of all buttons similar but it still isn't working. any help or advice at this point will be greatly appreciated!!
.categories-buttons {
display: grid;
grid-template-columns: 80px 80px 80px 80px 80px;
}
.item {
padding: 10px;
}
<div class="categories-buttons">
<button id="demo" class="item"></button>
<script>
for (var i = 0; i < 20; i++) {
document.getElementById("demo")(7);
}
</script>
</div>
Upvotes: 0
Views: 1293
Reputation: 87
Lets assume your list is an array of elements:
// This is javascript array of objects, each object has 1 property - buttonText.
// You can add more properties.
const elements = [
{ buttonText: 'Button 1' },
{ buttonText: 'Button 2' },
{ buttonText: 'Button 3' }
];
// Get parent div in which you want to add buttons
const parent = document.getElementById('buttons-container');
// In for loop, set "i" to be lower than number length of array.
for(let i = 0; i < elements.length; i++) {
// Create button node and add innerHTML (innerHTML is stuff that goes between <></> tags).
// Since "elements" is an array, you select current iteration of it with [i]
let button = document.createElement('button');
button.innerHTML = elements[i].buttonText;
parent.appendChild(button);
}
<div id="buttons-container"></div>
Upvotes: 1
Reputation: 816
Something like this?
.categories-buttons {
display: grid;
grid-template-columns: 80px 80px 80px 80px 80px;
}
.item {
padding: 10px;
}
<div class="categories-buttons">
</div>
<script type="text/javascript">
var div = document.getElementsByClassName("categories-buttons")[0];
for (var i = 0; i < 20; i++) {
var btn = document.createElement("button");
btn.innerText = "Button " + i;
div.append(btn);
}
</script>
Upvotes: 0