Having trouble getting my list items to display on individual lines within the foreach loop. It just doesn't seem to be working as expected

In the event listener, I need to ensure that my list items within the forEach loop are not displaying on separate lines. This issue is causing a problem in a lengthy section of code.

The goal is to update questions when an answer is clicked from a list. Both the questions and answers are stored in an array of objects for a coding quiz.

These list items are dynamically generated within the script, as shown below.

function presentQuestions() {

    interval = setInterval(function () {
        timeCounter++;
        timeEl.textContent = timeCounter;
       
    }, 1000)
    askNow.innerHTML = " ";
    ansList.innerHTML = " ";
    for (var i = 0; i < questions.length; i++){
        
        var displayQuestion = questions[changeQuestion].title;
        var displayListQues = questions[changeQuestion].choices;
        askNow.innerHTML = displayQuestion;
    }
    displayListQues.forEach(function (domanda) {
        // setId++;
        var li = document.createElement('li');
        li.setAttribute('id', setId++);
        li.textContent += domanda;
        ansList.append(li);

        li.addEventListener('click', function (e) {
            e.preventDefault();
            askNow.innerHTML = " ";
            ansList.innerHTML = " ";
            changeQuestion++;
            displayQuestion = questions[changeQuestion].title;
            displayListQues = questions[changeQuestion].choices;
            displayListQues.forEach(function (ques) {
                    
                li.textContent += ques + "\n"; // Attempting to display them on separate lines similar to this li.textContent += domanda but it's not working.
                 
            })
            askNow.textContent = displayQuestion;
            ansList.append(li)
        })
    })
}

Answer №1

To achieve the desired effect, you need to include the question text followed by <br> in the innerHTML.

Example:

const li1 = document.getElementById("li1")
const li2 = document.getElementById("li2")
const ques = "xyz"

function addText1() {
  li1.textContent += ques + "\n";
}

function addText2() {
  li2.innerHTML += ques + "<br />";
}
<button onClick="addText1()">add to 1st using textContent and \n</button><br />
<button onClick="addText2()">add to 2nd using innerHTML and br tag</button>

<ul>
  <li id="li1"></li>
  <li id="li2"></li>
</ul>

If the variable ques contains HTML or special characters like & that should be displayed literally, you must use an htmlEncode function as shown below.

Another Example:

const li1 = document.getElementById("li1")
const li2 = document.getElementById("li2")
const ques = "xyz<a>pqr"

function addText1() {
  li1.textContent += ques + "\n";
}

function addText2() {
  li2.innerHTML += htmlEncode(ques) + "<br />";
}

function htmlEncode(input) {
  const textArea = document.createElement("textarea");
  textArea.innerText = input;
  return textArea.innerHTML.split("<br>").join("\n");
}
<button onClick="addText1()">add to 1st using textContent and \n</button><br />
<button onClick="addText2()">add to 2nd using innerHTML and htmlEncode and br tag</button>

<ul>
  <li id="li1"></li>
  <li id="li2"></li>
</ul>

Answer №2

Understanding this concept may be challenging, but it appears that you are attempting to insert CRLF into HTML by using newlines (i.e. ""\n"") within the textContext property of an li element.

It seems that newlines and other whitespace in HTML do not function correctly outside of <pre> tags and possibly some other newer HTML5 elements. You might be able to accomplish your goal with a <br> tag, but you will need to utilize HTML methods like document.createElement('br') or something similar to element.innerHTML = '<br>'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to Ensure the Footer Stays Beneath Your Image Gallery

After successfully keeping the footer at the bottom of other pages on my website, I'm facing a challenge with my photo gallery page. The footer stubbornly sits in the middle of the page. :( This is the HTML code for that particular page: html { ...

Why dashes are incompatible with inner <span> elements?

Is there a way to make hyphens work on text with <span> elements for highlighting without breaking the algorithm? I don't want a workaround like &shy;. The Code (sandbox: https://codepen.io/anon/pen/ayzxpM): .limit { max-width: 50px; ...

Navigating through two nested arrays in JavaScript to access an object

Having difficulty extracting the nested car values using JavaScript (lodash). Take a look at the JSON data below: { "cars":[ { "nestedCars":[ { "car":"Truck", "color" ...

Is there a way to prioritize the table row background color over the cell input elements background color?

After a user selects a table row, the row is assigned the class below: tr.selected { background-color:#FFA76C; } However, if there are input fields in the cells with background colors, they end up overriding the row's background color. (For instance ...

Experiencing slow loading times with a Next.js app in the development environment

Currently, I am in the process of building a Next.js application and I have noticed that it takes quite a long time to load in the development environment. At the start, the page becomes unresponsive and if I cancel the request, it stops loading altogeth ...

Accessing the phone number input from a form in Rails and verifying its presence in the database. Implementing distinct ajax responses based on the existence of the value

Looking for a way to verify phone numbers? The process involves users entering a phone number, submitting the form, and cross-referencing it with a database of phone number records to determine if it's valid. My goal is to provide different AJAX respo ...

Encountering an Issue Executing Selenium Test on jQuery v2.0.2 and Play Framework

While I may not be a selenium expert, it seems that I've stumbled upon a bug when trying to utilize jQuery v2.0.2 with my Play Framework 2.2.1 application instead of the default jQuery v.1.9.0. Whenever I run "play test", I encounter the following err ...

How can I track the number of correct answers in a ReactJS quiz with an auto-submit feature and a timer that stops?

The auto-submit feature is not functioning correctly. Although the code works fine when I manually submit the quiz at the end, if the time runs out, the score will always be 0/3 which is incorrect. // React and Material-UI imports omitted for brevity // ...

The actions performed within an event listener function are undone once they have been carried out

I'm a newcomer to Javascript and I am currently experimenting with it. While browsing through a tutorial on w3schools, I came across an example of changing the color of a button after clicking on it. My idea was to take it a step further by loading a ...

What are the steps for configuring clusters in an expressjs 4.x application?

I currently have an expressjs generated app that is configured with socket io and I want to incorporate nodejs clusters into it. However, the challenge lies in the fact that in Express 4.x, the server listening configuration now resides in the bin/www file ...

How can I get electron to interact with sqlite3 databases?

I've exhausted all my options and still can't get it to function. This error message keeps popping up: https://i.stack.imgur.com/D5Oyn.png { "name": "test", "version": "1.0.0", "description": "test", "main": "main.js", "scripts": { ...

Images refusing to display within the div

I am attempting to insert an image onto my website, however, I am encountering issues with the code I have written: div#planet { z-index: -10; width: 450px; height: 549px; position: absolute; background: url("https://example.com/im ...

When transmitting JSON data from the View to the Controller in ASP.NET MVC, the received values are

I'm facing an issue with sending JSON data from an MVC View to Controller. All I seem to get in the Controller is: https://i.sstatic.net/4pKNF.png The JSON I send in Url.Action looks like this: (I create it myself by adding arrays together using .pu ...

Is it common for content to duplicate when using the 'position: fixed' property in CSS media print?

Consider the following div element: ... <div id='section-to-print'>CONT /*Content*/ </div> ... Accompanied by this CSS code snippet: @media print { * { -webkit-transition: none !important; ...

Tips for preventing 404 errors in react-router

I am currently working on a project using React Router and created it using create-react-app. Everything runs smoothly on my local server with links like localhost:3000/login and localhost:3000/product. However, when I deployed the project to my domain, ...

What is the best way to vertically align my image for perfect centering?

On one of my pages at , there is a section titled "FREE PICK UP AND RECYCLING OF LARGE QUANTITIES OF ELECTRONICS" with a picture of a truck. The image is perfectly centered vertically between the pictures on its left and right. Another page I have at fea ...

JS : Removing duplicate elements from an array and replacing them with updated values

I have an array that looks like this: let arr = ['11','44','66','88','77','00','66','11','66'] Within this array, there are duplicate elements: '11' at po ...

I encountered an issue while trying to integrate react-alert into my React application. An Uncaught Error was thrown, stating that objects are not valid as a React

I encountered the following error: react-dom.development.js:14748 Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead. in Unknown (c ...

Difficulty encountered while deploying a React application on Netlify

I followed the instructions on a Medium link to deploy my React application on Netlify: To set up the production mode, I utilized an express server for defining build scripts. After creating the build scripts on my local machine, I uploaded them to the Ne ...

When using videojs, I have the ability to include a Text Track event handler, however, there is currently no option to remove it

I implemented a listener for the 'cuechange' event on a Text Track and it's functioning correctly. However, I am unable to figure out how to remove this listener. I have attempted the instructions below to remove the listener, but it continu ...