i am trying to command a ul with javascript. But I run into the problem that it doesn't order it and part of it only captures two li, my current code is as follows:
function ordenarLista(){
var vaciar = '';
var ul = document.getElementById("listaCanciones");
var li = document.createElement("li");
var arrayCanciones = new Array();
var lista = ul.getElementsByTagName("li");
//lista la transformamos en un array
for(var i=0; i<lista.length;i++){
//para añadir elementos a un array push
arrayCanciones.push(lista[i]);
//ordenamos el array
console.log(arrayCanciones.sort());
//agragamos las canciones a la lista
li.appendChild(arrayCanciones[i]);
}
//pinchamos li en el DOM
ul.appendChild(li);
}
The first image shows the data entry of a simple form.
the second the result of clicking sort and the resulting console.log.
I do not know why it only captures two li and does not order.
I appreciate all help.
I pass you this solution with comments of the steps followed and based on this SO answer.
Although you already have an answer, I want to supplement it with the following solution.
I don't know exactly how you're adding and removing elements to your element
ul
, so I've implemented my own methods.In the method
sortSongs
, I simply use a function that performs the check on theArray
ofchildNodes
. In this comparison I order in ascending order.On the other hand, every time an element is added to
ul
, I assign an attributeid
to it dynamically usingDate.now
, so I can choose the element to remove.