1

I'm currently trying to first generate string and then set some text-content on my webpage to this string. This string consists of multiple Javascript objects. I would like each of these objects to be printed on a new line. For all I know, I can simply add \n after each object within my string and it should work. However, it doesn't. Here is my code:

function stringifyObjects(objects) {    
    if (objects.length > 0) {
        str = objects.slice(0, 5).reduce( function (acc, o) { 
            return acc + " " + stringifyObject(o) + "\n"
        }, "") 
        if (objects.length > 5) {
            str = str + " and " + (objects.length - 5) + " more"
        }
        console.log(str)
        return str               
    } else {
        return "No objects to show"
    }    
}

function stringifyObject(object) {
    const content = JSON.stringify(object.content).replaceAll('"', '')
    return message.type + ": " + content 
}

paragraph.textContent = stringifyObjects(someObjects)

The console.log() seems to work just fine, showing every object on a seperate line. Within the paragraph however, there are no newlines. Example below:

enter image description here

Any idea what might be causing this and how I would resolve this?

Astarno
  • 405
  • 3
  • 10
  • 4
    In HTML you need `
    `
    – j08691 Apr 20 '23 at 13:54
  • Do you know how whitespace is handled in HTML? See [Why doesn’t JavaScript newlines work inside HTML?](https://stackoverflow.com/questions/5782409/why-doesn-t-javascript-newlines-work-inside-html) – Wyck Apr 20 '23 at 13:54
  • How would I adjust my code to add these `
    ` tags? I assume I cannot simply replace `\n` by `
    `?
    – Astarno Apr 20 '23 at 13:57
  • 2
    You are writing HMTL source from JavaScript, so use `
    ` in the string. You will also need to assign it to `paragraph.innerHTML` instead of `paragraph.textContent`, to make the brower parse the string as HTML markup.
    – traktor Apr 20 '23 at 14:07

0 Answers0