0

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>
1

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.