Insert elements using Javascript insertBefore

Asked

Viewed 792 times

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"?

1 answer

1


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

So for your code to work you must specify the element index, as 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.