Search code examples
javascripthtmlpolymer

How to create linebreaks after joining strings from an array and rendering it inside a div?


I have the following array:

results = ["Dog","Cat","Fish","Parrot"];

I join it using the .join method like so:

var finalResult=results.join("\n");

I have a div:

Validation Result:<div id="result"></div>

I then try to render it inside a div like so:

this.shadowRoot.getElementById('result').textContent = finalResult;

This just ends up being rendered with a space between each word:

Dog Cat Fish Parrot

I want it to paste each string on a new line like so:

Dog

Cat

Fish

Parrot

I can't seem to be able to achieve this. Any suggestions on how I can achieve this?


Solution

  • Using <br> instead of \n will solve your issue.

    Maybe you can try as the following:

    const results = ["Dog","Cat","Fish","Parrot"];
    const div = document.getElementById('elements');
    div.innerHTML = results.join('<br>');
    <div id="elements"></div>

    Suggested articles to read:

    1. Element.innerHTML
    2. <br>: The Line Break element

    I hope that helps!