2

Trying to dynamically update the choices in the trivia game using a for loop with jQuery append, but the browser is not rendering the choiceText variable.

    for (let i = 0; i < allChoices[0].length; i++) {
        let allChoicesFin = allChoices[0];

        const choiceContainer = $('.choice-container');

        let choiceText =
            '<span class="px-2 text-start">' + allChoicesFin[i] + '</span>';

        choiceContainer[i].append(`${choiceText}`);
    }

picture of the trivia game where the HTML is not rendering

1
  • Hello and welcome. Instead of "append", try to use innerHtml attribute. Commented Mar 7, 2021 at 21:10

1 Answer 1

1

The issue is because you're accessing the jQuery object by index. This will return an Element object, not a jQuery object, so you're using the native append() method, not the jQuery one. As such the string is injected as text content, not a DOM string.

To fix this change choiceContainer[i] to choiceContainer.eq(i):

let allChoices = [['foo', 'bar']];
let allChoicesFin = ['lorem', 'ipsum'];
const $choiceContainer = $('.choice-container');

for (let i = 0; i < allChoices[0].length; i++) {
  $choiceContainer.eq(i).append(`<span class="px-2 text-start">${allChoices[0][i]}</span>`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="choice-container"></div>
<div class="choice-container"></div>

Note that I made a couple of tweaks to the logic to tidy it up a little, such as defining $choiceContainer outside of the loop, removing one unnecessary template literal, and adding one which was necessary.

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

2 Comments

Thank you so much, Rory, just learned a whole heap! Would've taken hours figuring that out by myself!
No problem, glad to help

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.