Search code examples
javascriptclonenode

Is there way to target assign unique ids to items creating by cloning node?


I am creating a grid based on the size of the browser window. The javascript correctly builds the grid but then I have no way of targeting the individual elements as none carries an ID class. is there a way to assign this when it does the 'clone'?

The body contains the following, the clone targets the list class. Within each list class is a div class with a circle that is generated by CSS. Ideally I would be able to target both the list class AND the div class within it.

<div class="gallery">
  <h1>Dot Dot Dot Test</h1>
  <ul class="gallery__list span1">
    <li class="center repeat">
    <div class="circle">
    </div>
    </li>
  </ul>
<h1>That's All Folks!</h1>

Here is the javascript that I'd like to automatically generate unique ids at the point it builds the grid.

<script>
        var w = window.innerWidth;
        var h = window.innerHeight;
        var numberOfColumns = Math.round(w/40);
        var numberOfRows = Math.round((h-200)/40);
        var numberOfDots = numberOfColumns * numberOfRows;
    function backgroundDots(node, count, deep) {
        for (var i = 0, copy; i < count - 1; i++) {
        copy = node.cloneNode(deep);
        node.parentNode.insertBefore(copy, node);

    }
}

backgroundDots(document.querySelector('.repeat'), numberOfDots, true);


    
    </script>

Any help much appreciated. Have been trying and searching quite a while but can't seem to make work/find solution.

Thanks,

Rob


Solution

  • Not sure if I got you right but you can set an id (or any other attribute) before inserting it on DOM. Something like:

      ...
      copy = node.cloneNode(deep);
      copy.id = `id-${i}`;
      node.parentNode.insertBefore(copy, node);
      ...