2

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?

2
  • 2
    The issue with your attempt was the usage of textContent instead of innerHTML. textContent is, as it suggest, going to be interpreted as just text Commented Jan 7, 2020 at 22:30
  • 1
    var finalResult=results.join("<br>"); Commented Jan 7, 2020 at 22:33

2 Answers 2

6

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!

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

1 Comment

2

The answer from @norbitrial is great and solves the issue. I'm hoping it's accepted as the correct solution, because it is.

The solution below is an alternative, which allows the use of the \n as a line break, and textContent property. The trick is to use a <pre> element.

results = ["Dog", "Cat", "Fish", "Parrot"];
const finalResult = results.join("\n");
document.getElementById('result').textContent = finalResult;
<pre id="result"></pre>

Comments

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.