0
I’m trying to perform an insertion operation on my Javascript code, but I’m having some difficulty using the insertBefore function.
First I’m creating an "ul" type element and performing its insertion in this way:
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 element created earlier, performing 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 am trying to add the "li" type element, but specifically in the insertBefore line. Reading the available documentation here i would need a reference within the element "ul" which at the time I do not have, would have some other way to add that element "read"?