0

So I wrote a simple form input that takes in a name and then displays it in a list below using li.innerHTML = "". I want to know would there be any difference if I used li.appendChild(document.createTexNode("blabla"));

const form = document.querySelector("#myForm");
const btn = document.querySelector("#submitBtn");
const name = document.querySelector("#nameInput");
const msg = document.querySelector(".msgBox");
const namesList = document.querySelector("#userList");

var i = 1;

form.addEventListener("submit", (e) => {
    e.preventDefault();
    if (name.value === "")
    {
        msg.innerHTML = "Please enter a name!";
        setTimeout(() => msg.remove(), 2000);
    } else {
        const li = document.createElement("li");
        li.innerHTML = name.value;
        namesList.appendChild(li);
        name.value = "";
    }
})

HTML file (if needed)

<html>

  <head>
    <meta charset="UTF-8" />
    <title>My Page</title>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>

  <body>
    <h1>Unesite ime</h1>
    <div class="msgBox"></div>
    <form id="myForm">
      <input id="nameInput" type="text">
      <input type="submit" id="submitBtn" value="Submit">
    </form>
    <ol id="userList"></ol>
  </body>
  <script src="main.js"></script>
</html>
57_Pixels
  • 5
  • 4
  • This seems to be a duplicate: https://stackoverflow.com/questions/13122760/is-there-any-major-difference-between-innerhtml-and-using-createtextnode-to-fill – Dustin Gogoll Apr 03 '19 at 08:13
  • 1
    `innerHTML` is a property of a Node ... `document.createTexNode` creates a text node ... they are totally unrelated – Jaromanda X Apr 03 '19 at 08:13

1 Answers1

1

document.createTextNode Creates a new Text node. This method can be used to escape HTML characters whereas innerHTML is used to get or set the HTML content of an element node.

If you like to update something with html then innerHTML do the job for you otherwise document.createTextNode is the safer function.

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29