简体   繁体   中英

Copy selected <li> to another <ul> with js

function addSelected(clicked_id) {
  // alert(clicked_id);
  const ul = document.getElementById("sortable2");
  const listItems = ul.getElementsByTagName("li");
  //   const ul2 = document.getElementById('slottable1');

  // Loop through the NodeList object.
  for (let i = 0; i <= listItems.length - 1; i++) {
    if (listItems[i].className == "selectedli") console.log(listItems[i]);

    //need to copy these <li> tags in another <ul> list
  }
}

<ul id="slottable">
//need to copy selected <li> here and also remove class from those selected <li> before adding here
</ul>

output of the console:

<li id="pc_103" class="selectedli">B73</li>
<li id="pc_104" class="selectedli">B74</li>

I have successfully printed li which I want to copy to another ul in console logs but not able to find the right code to copy them to my another ul. I also need to remove the class 'selectedli' from the li before adding it to the ul 'slottable'.

The appendChild() method should work.

Like this:

sortable2.appendChild(selectedli)

To remove classes, use selectedli.classList.remove(selectedli)

You looking for something like that? It copied from one ul to the new ul and removes the class.

 const btn = document.getElementById('transfer'); btn.addEventListener('click', () => { // copy from slottable to sortable2 const ul = document.getElementById("slottable").children; const ul2 = document.getElementById("sortable2"); let lis = Object.values(ul); lis.map((el) => { el.classList.remove('selectedli'); el.innerText += ' (copied and without classs slectedli)' ul2.appendChild(el) }) ul.innerHTML = ''; });
 .green { background: green; }.gray { background: gray; }
 <ul id="slottable" class="gray"> <li id="pc_103" class="selectedli">B73</li> <li id="pc_104" class="selectedli">B74</li> </ul> <ul id="sortable2" class="green"></ul> <button id="transfer">click </button>

It's done by creating dynamic tag inside slottable .

See below example:

 const getChild = document.getElementById("sortable2").children; const pickNewUl = document.getElementById("slottable"); function addSelected() { for (let i = 0; i < getChild.length; i++) { if (getChild[i].className == "selectedli") { var createLi = document.createElement("li"); createLi.id = getChild[i].id createLi.classList.add(getChild[i].classList); createLi.innerHTML = getChild[i].textContent; pickNewUl.appendChild(createLi); console.log(getChild[i]); } } document.getElementById("sortable2").innerHTML = ""; }
 <ul id="slottable"> </ul> <ul id="sortable2"> <li id="pc_103" class="selectedli">B73</li> <li id="pc_104" class="selectedli">B74</li> </ul> <input type="button" onclick="addSelected()" value="submit">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM