Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cloning an element multiple times with id

I have a li element parented to a ul with id holder. I need to clone the li multiple times, have all the clones parented to the holder ul and change their id. My hierarchy looks like this:

<ul id="holder">
<li>
 <label class="toggle-button">
  <input type="checkbox" id="1" onclick="toggleCheckbox(this)"/>
    <p class="neon" >MY1 </p>
  <i class="fa fa-power-off"></i>
 </label>
</li>
</ul>

How can I clone the li element and than change it’s id and MY1 so I get:

<ul id="holder">

<li>
 <label class="toggle-button">
  <input type="checkbox" id="1" onclick="toggleCheckbox(this)"/>
    <p class="neon" >MY: 1 </p>
  <i class="fa fa-power-off"></i>
 </label>
</li>

<li>
 <label class="toggle-button">
  <input type="checkbox" id="2" onclick="toggleCheckbox(this)"/>
    <p class="neon" >MY: 2 </p>
  <i class="fa fa-power-off"></i>
 </label>
</li>


<li>
 <label class="toggle-button">
  <input type="checkbox" id="3" onclick="toggleCheckbox(this)"/>
    <p class="neon" >MY: 3 </p>
  <i class="fa fa-power-off"></i>
 </label>
</li>

<li>
 <label class="toggle-button">
  <input type="checkbox" id="4" onclick="toggleCheckbox(this)"/>
    <p class="neon" >MY: 4 </p>
  <i class="fa fa-power-off"></i>
 </label>
</li>


</ul>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

use cloneNode to copy the li element and set the deep parameter to true to copy all the child nodes for that li element. Then use querySelector to target items within the clone and modify as required

let ul=document.getElementById('holder');
let li=ul.querySelector('li:first-of-type');

for(let i=0; i < 10; i++ ){
  let id=i+2;
  
  let clone=li.cloneNode( true );
      clone.querySelector('[type="checkbox"]').id=id;
      clone.querySelector('p').textContent=`MY: ${id}`;
      
  ul.appendChild( clone );
}
<ul id="holder">
  <li>
    <label class="toggle-button">
      <input type="checkbox" id="1" onclick="toggleCheckbox(this)"/>
      <p class="neon" >MY1 </p>
      <i class="fa fa-power-off"></i>
    </label>
  </li>
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading