0

I have a script that displays a random sentence on button click. I would like to add a line break to some of the sentences. Example:

"This is the first sentence"

becomes:

"This is
the first sentence"

I have tried using \n and <br>, but none works.
What else could I try?

    const p = document.getElementById("sentences");
    const origSentences = ["This is the first sentence.", "This is the second sentence.", "This is the third sentence."];
    let remainingSentences = [];

    function randomSentence() {
        if (remainingSentences.length === 0) remainingSentences = origSentences.slice();
        const {
            length
        } = remainingSentences;
        const [quote] = remainingSentences.splice(Math.floor(Math.random() * length), 1);
        p.textContent = quote;
    }
<p><button onclick="randomSentence()" type="button">Random Sentence</button></p>
<p id="sentences"></p>

1 Answer 1

1

If you assign your quote to the textContent field of your paragraph p, it will be rendered as plain text. If you instead use innerHTML, it will parse and render any HTML you provide.

See example.

const p = document.getElementById("sentences");
const origSentences = [
  "This is the <br /> first sentence.",
  "This is the second sentence.",
  "This is the <br /> third sentence."
];
let remainingSentences = [];

function randomSentence() {
  if (remainingSentences.length === 0)
    remainingSentences = origSentences.slice();
  const { length } = remainingSentences;
  const [quote] = remainingSentences.splice(
    Math.floor(Math.random() * length),
    1
  );
  p.innerHTML = quote;
}
<p>
  <button 
    onclick="randomSentence()" 
    type="button">
    Random Sentence
  </button>
</p>

<p id="sentences"></p>

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

1 Comment

Thanks! It fixed my problem! I was unaware of that difference between textContent and innerHTML. I guess I still have a lot to study.

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.