Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add <br> tag on dom(vanilla javascript)? I can't display my next loop on new line

const start = document.getElementById("start");
const end = document.getElementById("end");
const btnShowEven = document.getElementById("showEven");
const display = document.getElementById("display");

const br = document.createElement("br");

btnShowEven.addEventListener("click", myFunction);

function myFunction() {
  for (let i = start.value; i <= end.value; i++) {
    if (i % 2 == 0) {
      console.log(`${i} is an even number.`);

      display.textContent += `${i} is an even number.`;
      display.createElement += br;
    }
  }
}

how to add
tag on dom(vanilla javascript)? I can’t display my next loop on new line.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="main.css" />

    <title>Document</title>
  </head>
  <body>

    <input type="text" id="start" />
    <input type="text" id="end" />
    <button id="showEven">Show even numbers</button>
    <hr />
    <p id="display"></p>

    <script src="main.js"></script>
  </body>
</html>

I am a beginner here. Sorry. Here is my HTML file.
The output is all my loop displays in 1 line.
I wanted to display all even numbers in new line.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here’s an easy solution. Just use innerHTML instead of trying to create new elements.

const start = document.getElementById("start");
const end = document.getElementById("end");
const btnShowEven = document.getElementById("showEven");
const display = document.getElementById("display");

const br = document.createElement("br");

btnShowEven.addEventListener("click", myFunction);

function myFunction() {
  for (let i = start.value; i <= end.value; i++) {
    if (i % 2 == 0) {
      console.log(`${i} is an even number.`);

      display.innerHTML += `${i} is an even number.<br>`;
    }
  }
}
<input value="1" id="start">
<input value="10" id="end">
<button id="showEven">Click</button>
<div id="display"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading