I’m trying to insert <hr>
between first and second .field-container
. Both share the same parent so, element1.parentNode.insertBefore(element2, ...)
should work. It’s not working and I’m getting an error instead.
(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>
By appending hr
first to the parent element then trying to insert it between both containers fixes the error but the insertion happens at the end, not between.
(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>
3
Answers
insertBefore(newNode, referenceNode)
Since you need the
hr
beforecontainers[1]
your
newNode
or node to be inserted is thehr
and thereferenceNode
or node before which newNode is inserted is thecontainers[1]
Comments
insertBefore(containers[1], hr)
do thisinsertBefore(hr, containers[1])
JS