KOMPX.COM or COMPMISCELLANEA.COM   

Append an element after a specific element in JavaScript

Appending an element after a specific element in plain JavaScript. Emulating non-existent insertAfter() method, by combining insertBefore() with Node.nextSibling:

Child 1
Child 2
Child 3

HTML code:


<div class="example">
	<div class="child_1">Child 1</div>
	<div class="child_2">Child 2</div>
	<div class="child_3">Child 3</div>
</div>

JavaScript code:


<script>
var element_before = document.querySelector('.child_2').nextSibling;
var element = document.createElement('div');
element.classList.add('element');
element.textContent = 'Element';

document.querySelector('.example').insertBefore( element, element_before );
</script>

Links

  1. Node: insertBefore() method: developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
  2. Node: nextSibling property: developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling
  3. «There is no insertAfter() method. It can be emulated by combining the insertBefore method with Node.nextSibling»: developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore#sect3
Browser support
Windows
Internet Explorer 9.0+
Edge 12.0+
Firefox 3.5+
Google Chrome 1.0+
Opera 10.0+
Safari 3.1+
Linux
Firefox 3.5+
Google Chrome / Chromium
Opera 10.0+
iOS
Safari 2.0+
Android
Samsung Internet 1.0+
Chrome 18.0+
Firefox 4.0+
Opera 10.1+
More