T.Todua
T.Todua

Reputation: 56555

Append html(text) to element without affecting siblings?

I always use appendChild to add something to other element, because if I use:

innerHTML +=  'added stringgggggggggg';

then this messes up the dynamic element,for example <form>, with filled values (it resets field values to empty).

Is there any shorter way to add smth to element, without appenChild and without using JQuery?

Upvotes: 2

Views: 1365

Answers (1)

Soviut
Soviut

Reputation: 91714

You can use element.insertAdjacentHTML() to evaluate and append a raw HTML string to an element.

element.insertAdjacentHTML('beforeend', '<p>put me inside at the end</p>');

By changing the position attribute you can insert before the element, after it, inside it at the beginning, or inside it at the end.

<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

Unlike innerHTML, insertAdjacentHTML() won't cause the browser won't to re-evaluate the entire DOM node you're injecting into, so form field values will be maintained.

var parentEl = document.getElementById('parent');
parentEl.insertAdjacentHTML('beforeend', '<p>this paragraph was inserted at the end of the form without affecting the form field values!<p>');
<form id="parent">
  <input type="text" value="insert something after form"><br>
  <input type="text" value="without affecting the values"><br>
  <input type="text" value="in the form fields"><br>
</form>

Upvotes: 5

Related Questions