Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to insert new element between 2 elements having the same parent

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

insertBefore(newNode, referenceNode)
Since you need the hr before containers[1]
your newNode or node to be inserted is the hr and the referenceNode or node before which newNode is inserted is the containers[1]

(function() {
    let containers = document.querySelectorAll('.field-container');
    let hr = document.createElement('hr');
    // containers[0].parentNode.appendChild(hr); this not needed
    containers[0].parentNode.insertBefore(hr, containers[1]);
})();
<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading