Search code examples
javascriptparent-childclonenode

How to change id of parent and all its child elements in clone.Node


How to change id of parent and all its child elements in clone.Node?

I need to change id of parent and child, but only parent's id gets changed.

<div id="parent" style="border:1px solid black;background-color:pink">
  <div id="child1" style="color:red;">A r element</div>
  <div id="child2" style="color:green;">A g element</div>
  <div id="child3" style="color:blue;">A b element</div>
</div>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  var elmnt = document.getElementById("parent");
  var elmntid = document.getElementById("parent").id;
  var cln = elmnt.cloneNode(true);
  cln.id = elementid + "copy";
  document.body.appendChild(cln);
}

Solution

  • If you want to append something to all the cloned elements' IDs, you can do something like this:

    document.querySelector('#button').addEventListener('click', () => {
      const clone = document.querySelector('#parent').cloneNode(true);
      const elementsThatHaveId = [...clone.querySelectorAll('[id]')];
      if (clone.matches('[id]')) {
        elementsThatHaveId.push(clone);
      }
      elementsThatHaveId.forEach((e) => {
        e.id += 'Copy';
      });
      document.body.append(clone);
    });
    <div id="parent" style="border:1px solid black;background-color:pink">
      <div id="child1" style="color:red;">A r element</div>
      <div id="child2" style="color:green;">A g element</div>
      <div id="child3" style="color:blue;">A b element</div>
    </div>
    
    <button id="button">Try it</button>

    What this does is to select all elements of the cloned node that have an id attribute (clone.querySelectorAll('[id]')), add the node itself to the result array if it has an id attribute as well and then go through the list to modify all those elements' IDs