Search code examples
javascriptjqueryhtmlbuttonclone

How to clone div and insert button together?


I just want to clone and insert button in right handed-side of this cloned one.

my javascript looks like this:

 $('.frame .portlet').click(function (e) {


        if ($(e.target).is(".portlet-content") || $(e.target).is(".portlet-header")) {
            cancel: 'ui-icon-minusthick ui-icon-plusthick';
            var $this = $(this), $error;

            // for duplicate
            if ($this.hasClass('added') && !$this.hasClass('newPortlet')) {
                $error = $this.next('.clone-error');
                if (!$error.length) {
                    $error = $('<span />', {
                        'class': 'clone-error',
                        html: '<div class="alert alert-warning" role="alert" style="width: 300px"> This question is already added!</div>'
                    }).insertAfter(this);
                }
                $error.stop().show().delay(800).hide(1);
            } else if (!$this.hasClass('newPortlet')) {
                $this.addClass('added').clone(document.getElementById(this.id)).addClass('newPortlet').("<button>hi</button>").appendTo('#creation .newFrame');

                $msg = $('<span />', { html: '<div class="alert alert-success" role="alert" style="width: 300px"> This question is added to Add List!</div>' }).insertAfter(this);
                $msg.stop().show().delay(800).hide(1);
                count++;
                add.html("<span id='newExam' class='badge' style='background-color: lightgreen; border-color: green'>" + count + "</span>");
            }

        }
    });

I want it to be like this:

enter image description here


Solution

  • You can store a reference to the cloned object....then manipulate that object by appending to it.

    Change:

    $this.addClass('added').clone(document.getElementById(this.id))
          .addClass('newPortlet').appendTo('#creation .newFrame');
    

    To:

      // create clone object
      var $clone = $this.addClass('added').clone(this);
      // now can append to clone
      $clone.append('<button>TEST</button>');
      // then insert clone to dom          
      $clone.addClass('newPortlet').appendTo('#creation .newFrame');
    

    By creating the object as variable it makes it much easier to read and see various steps. I think your main issue was just having to many steps in a chain to make logic easy to follow

    DEMO