Search code examples
javascriptjqueryhtmlclone

Jquery Clone and Update All ids


I want to clone a div using it's id with many elements inside it which also has their own id that I want to change after cloning.

Consider this HTML structure:

<div id='wrapper1'>
  <p id='test1'>Hello</p>
  <p id='my-awesome-id1'></p>
</div>

I found this on SO but it only changes the id of the main element you cloned and not the children.

Is there a way I could do it so that I could update all of the 1 into 2 and so on?


Solution

  • This would do it and create a clone like:

    <div id="wrapper2">
      <p id="test2">Hello</p>
      <p id="my-awesome-id2"></p>
    </div>
    

    $('div').clone().filter(function() {
      $(this).prop('id', $(this).prop('id').replace('1', '2')).children().filter(function() {
        return $(this).prop('id', $(this).prop('id').replace('1', '2'))
      });
      return $(this)
    }).appendTo('body')
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id='wrapper1'>
      <p id='test1'>Hello</p>
      <p id='my-awesome-id1'></p>
    </div>