April 22, 2012

unable to create multiple div inside div dynamically

Question by prerna

$.post("../../Handler/Topic.ashx", 
       { commentclob: commentClob, 
         commenttitle: commentTitle,
         topicId: id, 
         Button: buttoname },
       function (data) {
         obj = jQuery.parseJSON(data);
         var $table = $('<table/>').addClass('commentbox');

         $table.append('<tr><td>' + 
                       'Comment Id:' + 
                       obj.CommentId + 
                       '</td></tr>');

        var includeReply = "<input type='button' 
                                   class='btnReply' 
                                   value='Reply' 
                                   id='btnReply-" + obj.CommentId + "' />";


        $("#commentContainer").prepend(
          $('<div/>').attr('id', '#comment-' + obj.CommentId)
                     .append($table)
        );

        //This doesnt work         
        $("#comment-" + obj.CommentId).append(
          $('<div/>').attr('id', '#container-' + obj.CommentId)      
                     .append(includeReply)
        );
});

html

  <div id="commentContainer"></div>

I am successfully able to append div with #comment-id to comment-container but I am unable to append another div inside #comment-id.

I have tried

               var str = $("<div>").attr("id", "#container-" + obj.CommentId)
               $(str).append(includeReply);
               $table.append('<tr><td>' + 'CommentDiv:' + str + '</td></tr>');

But it gives

CommentDiv:[object object]

Answer by Starx

str is an HTML object so it can concatenated like that. You have to extract the markup with .html() and then concatenate it.

   var str = $("<div>").attr("id", "#container-" + obj.CommentId)
   $(str).append(includeReply);
   $table.append('<tr><td>' + 'CommentDiv:' + str.html() + '</td></tr>');

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!