Weird side effect of innerHML plus equal (+=) : use .insertAdjacentHTML instead

I was using pure HTML and Javascript, adding some <select> or <input> to an element, using element.innerHTML += “<div><select>…</select></div>”

<div id="styles-forms-container-list">
  <input type="text">
  <select>...</select>
</div>

<button onclick="this.previousElement.innerHTML += '<select>...</select>'">Add style</button>

There was a weird bug, it was resetting other input in the list, I don’t understand why.

Well I did not find why, but I found that it is better to use insertAdjacentHTML instead, because innerHTML += parse the whole element again.

=> you should use element.insertAdjacentHTML("beforend", yourHtmlTemplate)

MDN documentation : insertAdjacentHTML


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *