how to add an id to an element created by means of a createElement ("tag");

1

I want to create a list, to which new elements are added by means of a input (that I already did). But now, I want to delete those elements when I click on them, the thing is that I do not know how to select them, since they do not have a id when creating them by means of a createElement("tag"); , I just wanted to know how to take that element to eliminate it by means of a removeChild()

    
asked by Juandev 10.09.2018 в 20:14
source

2 answers

1

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

    
answered by 10.09.2018 / 20:29
source
1

To assign a id or any attribute with createElement you have to use setAttribute , another option would be to modify the property id , I leave an example

//Opción uno, usando setAttribute
ej = document.createElement('input');
ej.setAttribute("id", "Input1");

//Opción dos, usando la propiedad id
ej2 = document.createElement('input');
ej2.id = "Input2"


document.getElementsByTagName('body')[0].appendChild(ej);
document.getElementsByTagName('body')[0].appendChild(ej2);
#Input1
{
  background-color: red;
}
#Input2
{
  background-color: cyan;
}
input{
display: block;
margin-top: 2px;
}
<body></body>

I clarify that the css is for demonstration purposes only.

    
answered by 10.09.2018 в 20:29