Insert elements using JavaScript insertBefore

0

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?

    
asked by anonymous 14.03.2016 / 01:51

1 answer

1

The getElementsByClassName function returns a list of elements that have a given class.

So for your code to work you must specify the index of the element, because in this scenario there is only one element with this class, you must use the first item in the list:

list[0].insertBefore(elemento, list[0].childNodes[0]);

Functional Example:

	var novaLista = document.createElement("ul");
	novaLista.setAttribute("class", "itens1 estilo-itens");

	var div = document.getElementById("lista");
	div.insertBefore(novaLista, div.childNodes[0]);

	var elemento = document.createElement("li");
	elemento.setAttribute("class", "item");
	var textoElemento = document.createTextNode("elemento");
	elemento.appendChild(textoElemento);

	var list = document.getElementsByClassName('itens1');
	list[0].insertBefore(elemento, list[0].childNodes[0]);
<div id="lista">

</div>
    
14.03.2016 / 02:16