After creating the element:
var elemento = document.createElement("div");
You can set any attribute as the id in the following way:
elemento.setAttribute("id", "idPrueba");
and then you can set a click event where I show you how to delete it:
var elemento = document.createElement("div");
elemento.setAttribute("id", "idPrueba");
elemento.onclick = function () {
alert("Soy un div");
alert("Me voy a borrar")
this.parentElement.removeChild(this);
};
document.body.appendChild(elemento);
#idPrueba{
border:1px solid red;
height:30px;
width:100%;
}
ANOTHER EXAMPLE AS YOU WANT IT:
var newElemento = document.createElement("div");
document.body.appendChild(newElemento);
var elementos = document.getElementsByTagName("DIV");
for (var i = 0; i < elementos.length; i++) {
elementos[i].setAttribute("id", "idPrueba"+i);
elementos[i].addEventListener("click", function(){
alert("Soy un div");
alert("Me voy a borrar")
this.parentElement.removeChild(this);
});
}
#idPrueba0{
border:1px solid red;
height:30px;
width:100%;
}
I hope I help you