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
- Node: insertBefore() method: developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
- Node: nextSibling property: developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling
- «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
- Accessing the first element in forEach loop (JavaScript)
- Adding a class to all sibling elements of a specific type in JavaScript
- Array to string in JavaScript
- Calculate sum of HTML table column in JavaScript
- Click event only on parent, not children
- Detecting a newly generated element and adding a class to it in JavaScript
- Detect if a class has been added (JavaScript)
- Generating an HTML list out of page headings in JavaScript
- Get the current URL in JavaScript
- Getting the last class name in classList collection
- Removing the last character from a string in Javascript
- Transliterating Russian to English in JavaScript
- Wrap each character of a string in <span> tag (JavaScript)
- Wrap each word of text in <span> tag (JavaScript)