I'm attempting to place an <hr>
tag between the first and second .field-container
. Because they have the same parent, I thought using
element1.parentNode.insertBefore(element2, ...)
would be the solution. However, it is not working as expected and instead, an error is being thrown.
(function() {
let containers = document.querySelectorAll('.field-container');
let hr = document.createElement('hr');
containers[0].parentNode.insertBefore(containers[1], hr);
})();
<div>
<div class="field-container">
<input placeholder="Field 1" type="text">
<span></span>
</div>
<div class="field-container">
<input placeholder="Field 2" type="text">
<span></span>
</div>
</div>
Adding the hr
tag directly to the parent element before trying to insert it between the containers resolves the error. However, the insertion then occurs at the end rather than between the two elements.
(function() {
let containers = document.querySelectorAll('.field-container');
let hr = document.createElement('hr');
containers[0].parentNode.appendChild(hr);
containers[0].parentNode.insertBefore(containers[1], hr);
})();
<div>
<div class="field-container">
<input placeholder="Field 1" type="text">
<span></span>
</div>
<div class="field-container">
<input placeholder="Field 2" type="text">
<span></span>
</div>
</div>