EN VI

Javascript - Function fails to create buttons on html document?

2024-03-12 17:00:08
How to Javascript - Function fails to create buttons on html document

So I followed a tutorial to write this. Its supposed to replace main text and some buttons on a html div. Its setting the text and removing the buttons correctly. It just does not add the correct buttons in, so im left with no buttons.

}

function ShowTextNode(textNodeIndex) {
    const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
    textElement.innerText = textNode.text
    while (optionButtonsElement.firstChild) {
        optionButtonsElement.removeChild(optionButtonsElement.firstChild)
    }

    textNode.options.foreach(option => {
        if (showOption(option)) {
            const button = document.createElement('button')
            button.innerText = option.text
            button.classList.add('btn')
            button.addEventListener('click', () => SelectOption(option))
            optionButtonsElement.appendChild(button)
        }
    })
}

function showOption(option) {
    return option.requiredState == null || option.requiredState(state)
}

Here's how a nextnode and its options are defined:

const textNodes = [
    {
        id: 1,
        text: "this is index 1 text",
        options: [
            {
                text: "option 1 for index one page",
                setState: {tookoption1: true},
                nextText: 2
            },
            {
                text: "option 2 for index one page",
                nextText: 2
            }
        ]
    },
]

I'm really new to this so it's probably a missing coma or something that I can't spot. Just trying to learn by making a text adventure.

Solution:

looks like there's a small typo in your code. the method to iterate over each item in an array is forEach, not foreach

textNode.options.forEach(option => {
    if (showOption(option)) {
        const button = document.createElement('button');
        button.innerText = option.text;
        button.classList.add('btn');
        button.addEventListener('click', () => SelectOption(option));
        optionButtonsElement.appendChild(button);
    }
});
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login