Search code examples
javascripthtmlformsappendchild

appendChild not working on some elements


I'm working on a vanilla javascript project so I cannot use jQuery. I'm trying to use the following to move some HTML from one placement to another:

parent.appendChild(element);

I'm trying to place the forms into a different placement as I placed in the comment in my HTML code. I'm trying this but it's not working at all.

Javascript:

var loginButton = document.querySelector('[data-login-header-button]');
var loginDropdown = document.querySelector('[data-login-dropdown]');

var shopCartButton = document.querySelector('[data-shopping-cart-header-button]');
var shopCartDropdown = document.querySelector('[data-shopping-header-cart]');

shopCartButton.parentNode.appendChild(shopCartDropdown);
loginButton.parentNode.appendChild(loginDropdown);

HTML:

<header>
    <nav data-nav-services>
        <ul class="nav-services">
            <li data-test>
                <a class="icon icon-shopping-cart icon-arrow-down" href="#" data-shopping-cart-header-button>
                    shopping cart
                </a>
                <!-- PLACEMENT FOR data-shopping-header-cart -->
            </li>
            <li>
                <a class="icon icon-user icon-arrow-down" href="#" data-login-header-button>
                    Login
                </a>
                <!-- PLACEMENT FOR data-login-dropdown -->
            </li>
        </ul>
    </nav>

    <form class="login-dropdown" data-login-dropdown>
        ...CONTENT...
    </form>

    <form class="shopping-cart" data-shopping-header-cart>
        ..CONTENT..
    </form>
</header>

The strange thing is that if I turn around the selectors (as here below) it does work and I cannot explain why...

shopCartDropdown.parentNode.appendChild(shopCartButton);
shopCartDropdown.parentNode.appendChild(loginButton);

Solution

  • For anybody who wish to know, the code was perfect. The issue was that I was appending this form elsewhere of my code. So there was a conflict as one had a priority over the other. I could use .cloneNode(true) as a solution. I ended transforming that appending to my new goal and solved the issue.

    Anybody out there... check all the code for any other appending of the same element. Good advice ;)