Search code examples
javascriptjqueryjquery-post

jQuery appendTo does not work under $.post


// plays a card into table.
// this code works. rendered card is appending into the table.
    var playCard = function(card){
        var renderedCard = renderCard(card);
        $('#'+renderedCard.id).appendTo('#flop');

// but this one does not work.
var playCom = function(){
        $.post('/api/comPlay', function(data){
            var renderedCard = renderCard(data.card);
            $('#'+renderedCard.id).appendTo('#flop');
        });
    };

I check the returned value from $.post. data.card gives the correct value. I create a div html with my renderCard function. That function works correctly as you see. But under $.post not.

I am stuck. Is there something special that i must know about $.post?

Thank you.

update :

var renderCard = function(card){
        var create = document.createElement('div');
        create.className = 'cardBig';
        create.id = card;
        return create;
    };

Solution

  • You don't need to "find" your newly-created DOM element.

    $(renderedCard).appendTo('#flop');
    

    should do it.

    Also, since you're using jQuery anyway:

    $('#flop').append($('<div/>', {
      className: 'cardBig',
      id: data.card
    }));
    

    will save you the extra function.