In this code:
let container = document.getElementById('variables'); Array.from(container.querySelectorAll('tr')) .sort((a, b) => a.getAttribute("name").localeCompare(b.getAttribute("name"), )) .forEach(tr => container.appendChild(tr));
<table id="variables"> <tr name=B> <td>B</td> </tr> <tr name=A> <td>A</td> </tr> <tr name=C> <td>C</td> </tr> </table>
I create an unsorted HTML table and sort it with JavaScript.
I works but I do not understand why I do not get the original array followed by the sort one because the forEach
do appendChild
to the original table
What is the magic behind this code?
foo.appendChild(bar)
puts bar
at the end of foo
.
Since an element can't exist in two places at the same time, if it was already the child of another element, it is removed from there first.
ie it is not the same as foo.appendChild(bar.cloneNode(true))
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.