the javascript function does not work twice

advertisements

i'm teaching myself to write native javascript, and i created this function that checks the div to see if it has children, and if not, then it creates a div with a class of 'card'.

the function works when i pass in an argument, but when i do it back to back, it ignores the first function instance and only outputs the second. any ideas?

thanks!

here's my code:

JavaScript:

var dealerCards = document.querySelector('.dealer-cards');
var playerCards = document.querySelector('.player-cards');
var newDiv = document.createElement('div');

function cardCheck(a){
    if (a.firstChild == null) {

        console.log(a.firstChild, a);

        newDiv.className = 'card';

        return a.appendChild(newDiv);

    }
}

cardCheck(dealerCards);
cardCheck(playerCards);

HTML:

<div class="dealer-box box">
    <h2>Dealer</h2>
    <div class="dealer-cards card-wrapper"></div>
</div>
<div class="player-box box">
    <h2>Player</h2>
    <div class="player-cards card-wrapper"></div>
</div>

http://jsbin.com/rehozu/1/edit?html,js


You have to create the new element inside the function. If you are appending an element that already exists in the document, the element is moved to its new parent, not cloned.

From the MDN documentation:

If child is a reference to an existing node in the document, appendChild moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).

This also means that a node can't be in two points of the document simultaneously. So if the node already has a parent, it is first removed, then appended at the new position.

You can use Node.cloneNode to make a copy of the node before appending it under the new parent. (Note that the copies made with cloneNode will not be automatically kept in sync.)