Home > Blockchain >  Cloning an element multiple times with id
Cloning an element multiple times with id

Time:01-11

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 >
  <input type="checkbox" id="1" onclick="toggleCheckbox(this)"/>
    <p  >MY1 </p>
  <i ></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 >
  <input type="checkbox" id="1" onclick="toggleCheckbox(this)"/>
    <p  >MY: 1 </p>
  <i ></i>
 </label>
</li>

<li>
 <label >
  <input type="checkbox" id="2" onclick="toggleCheckbox(this)"/>
    <p  >MY: 2 </p>
  <i ></i>
 </label>
</li>


<li>
 <label >
  <input type="checkbox" id="3" onclick="toggleCheckbox(this)"/>
    <p  >MY: 3 </p>
  <i ></i>
 </label>
</li>

<li>
 <label >
  <input type="checkbox" id="4" onclick="toggleCheckbox(this)"/>
    <p  >MY: 4 </p>
  <i ></i>
 </label>
</li>


</ul>

CodePudding user response:

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 >
      <input type="checkbox" id="1" onclick="toggleCheckbox(this)"/>
      <p  >MY1 </p>
      <i ></i>
    </label>
  </li>
</ul>

CodePudding user response:

you can try something like that:

let list = document.createElement("ul");
let numberOfListItems = 5; // set how many items in the list

function makeList(){

    let id = 1;

    for(i=0; i<=(numberOfListItems-1); i  ){

        let listelement = document.createElement("li");
        let label = document.createElement("label");
        label.className = "toggle-button";
        let input = document.createElement("input");
        input.setAttribute('type', 'checkbox')
        input.id = id;
        input.onclick = "toggleCheckbox(this)"
        let par = document.createElement("p");
        par.className = "neon"
        par.innerText = "MY:"   id
        let i = document.createElement("i");
        i.className = "fa fa-power-off";

        listelement.appendChild(label);
        listelement.appendChild(input);
        listelement.appendChild(par);
        listelement.appendChild(i);
        list.appendChild(listelement)

        id =1;
    }

}
  • Related