0

I have found two different ways to add a span element to the DOM, but I am unsure which is better to use in terms of best practices and performance.

    const letterEl = document.createElement('span')
    letterEl.textContent = letter
    textEl.appendChild(letterEl)

OR

    textEl.innerHTML += '<span>' + letter + '</span>'

textEl is a h1 element that will hold the span
letter is a string value

Tyler Morales
  • 1,440
  • 2
  • 19
  • 56
  • 1
    The second way is bad, because you're asking the browser DOM to do potentially much more work than it needs to. Remember, `e.innerHTML += "something"` is the same as `e.innerHTML = e.innerHTML + "something"`, so anything else that's inside the element gets re-added to the DOM when you do this. And DOM manipulation is usually the slowest part of any normal JS program. – Robin Zigmond Jan 04 '20 at 16:14
  • 2
    Does this answer your question? ["innerHTML += ..." vs "appendChild(txtNode)"](https://stackoverflow.com/questions/2305654/innerhtml-vs-appendchildtxtnode) – Emiel Zuurbier Jan 04 '20 at 16:14
  • setting `innerHTML` may result in XSS attack – Piekarski D Jan 04 '20 at 16:21

0 Answers0