javascript 多次克隆具有ID的元素

z0qdvdin  于 2023-01-11  发布在  Java
关注(0)|答案(2)|浏览(168)

我有一个li元素,它的父元素是一个带有id保持器的ul。我需要多次克隆li,将所有的克隆元素的父元素都设置为holder ul,然后更改它们的id。我的层次结构如下所示:

<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>

如何克隆li元素并更改其id和MY1,从而得到:

<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>
vdzxcuhz

vdzxcuhz1#

使用cloneNode复制li元素,并将deep参数设置为true以复制该li元素的所有子节点。然后使用querySelector定位克隆中的项,并根据需要进行修改

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>
hvvq6cgz

hvvq6cgz2#

你可以试试这样的方法

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;
    }

}

相关问题