0

I want to select a HTML element and append it to another div on a click of a button using Angular2. Startup HMTL

<div class="parent">
<ul class="level1">
    <li>
        <div class="otherdiv">
            This is a test
            <button md-raised-button type="button" color="primary">Clone</button>
        </div>
    </li>
</ul>

When the button is clicked I expect to have following structure

<div class="parent">
<ul class="level1">
    <li>
        <div class="otherdiv">
            This is a test
            <button md-raised-button type="button" color="primary">Clone</button>
        </div>
        <ul class="level2">
            <li>
                <div class="otherdiv">
                    This is a test
                    <button md-raised-button type="button" color="primary">Clone</button>
                </div>
            </li>
        </ul>
    </li>
</ul>

Not sure how can I achieve this. Any help appreciated. Thanks

1
  • thanks @Arvind Sivam, I missed that tag. Commented Mar 31, 2017 at 13:37

1 Answer 1

1

You can use clone() in jquery.

JSFIDDLE

Here is the code:

$('button').click(function() {
  $("#level1").clone().attr('id', 'level2').insertAfter("#level1");
});
<div class="parent">
  <ul id="level1">
    <li>
      <div class="otherdiv">
        This is a test
        <button md-raised-button type="button" color="primary">Clone</button>
      </div>
    </li>
  </ul>

Using angluarJs also we can do the same by using ng-repeat.You can repeat every time by adding the number.

ANGULAR FIDDLE

var app = angular.module('myapp', []);
app.controller('ctrlParent', function($scope) {
  $scope.myNumber = 1;
  $scope.myFun = function() {
    $scope.myNumber = $scope.myNumber + 1;
  }
  $scope.getNumber = function(num) {
    return new Array(num);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
  <div ng-controller="ctrlParent">
    <ul>
      <li ng-repeat="i in getNumber(myNumber) track by $index"><span>{{$index+1}}</span>
        <button ng-click="myFun()">Click to CLone
            </button>
      </li>
    </ul>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer but what I am looking for is angular 2 way of doing it(I know I can use jQuery in angular2 app too), still your answer is also appreciated.
@NiranjanNimbalkar check the solution using angularjs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.