I'm trying to perform an insert operation in my JavaScript code, but I'm having a hard time using the insertBefore function.
First, I'm creating an element of type "ul" and inserting it like this:
var novaLista = document.createElement("ul");
novaLista.setAttribute("class", "itens1 estilo-itens");
var div = document.getElementById("lista");
div.insertBefore(novaLista, div.childNodes[0]);
Now I'm trying to insert some elements of type "li" in this previously created element, making the following code:
var elemento = document.createElement("li");
elemento.setAttribute("class", "item");
var textoElemento = document.createTextNode("elemento");
elemento.appendChild(textoElemento);
var list = document.getElementsByClassName('itens1');
list.insertBefore(elemento, list.childNodes[0]);
But the following error is returned:
Cannot read property '0' of undefined
When I debug the code I realize that the error happens when I'm trying to add the element of type "li", but specifically in the line of insertBefore. By reading the available documentation here I would need a reference inside the element "ul" what on the occasion I do not have, would I have some other way to add this "li" element?