0
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
  <input type="text" name="item" id="input">
  <button id="b1">Add</button>
  <button id="b2">Add</button>
  <ul id="list">
  </ul>
  <script>
    let b1 = document.getElementById("b1")
    let b2 = document.getElementById("b2")
    let input = document.getElementById("input")
    let list = document.getElementById("list")

    b1.addEventListener("click", function () {
      if (input.value) {
        list.innerHTML += `<li>${input.value}</li>`  
      }
    })

    b2.addEventListener("click", function () {
      if (input.value) {
        let li = document.createElement("li")
        li.appendChild(document.createTextNode(input.value))
        list.appendChild(li)
      }
    })
  </script>
</body>
</html>

I am fairly new to javascript and came across multiple ways to get the same result.Would you prefer the #b1 function or the #b2 function and why?

  • 3
    Allowing the user input to be parsed as HTML results in XSS vulnerabilities. But `.textContent` is easier than `document.createTextNode` – CertainPerformance Feb 22 '23 at 06:41
  • So to be clear, your two functions don't do the same at all. In the first case if the user inputs some HTML, this will be parsed as HTML, and they'll even be able to execute scripts (what @CertainPerformance referred to as "XSS", though it's not *really*). For instance the input `` would show the alert box. The second code would just show the raw markup. It won't be parsed as HTML and no script will be executed. – Kaiido Feb 22 '23 at 07:03
  • However, to be pedantic, all your users would be able to do with this exact code is "self-XSS", something they can already do from their dev-tools. The real trouble starts when you read the data from somewhere else than your , e.g if it's saved on the server, or somewhere the user input might have been tempered by another actor, e.g the query-params of the page's URL. They can still be tricked into entering dangerous content in your inputs, but at this point, they can certainly be tricked into doing a lot worse things. – Kaiido Feb 22 '23 at 07:03

0 Answers0