Good Morning. First of all I apologize for how unclear the title is, I couldn't describe it better. Secondly, I clarify that what I am going to put here is an invented and simple example so that you understand what my question is and avoid unnecessarily complicating ourselves trying to solve my question in my code.
The example is as follows: On the page there is an input to write and a button. When the button is pressed, the following function is executed: -Using an innerHTML, create an html element (a span) with the value of the input as id. -I also want it to create an addEventListener on that object, but of course, I only have the id of that span stored in the variable and I don't know how to use the variable to refer to each of the spans that are created.
document.addEventListener("DOMContentLoaded", function(){
var listaSpan = "";
document.getElementById("boton").addEventListener('click', function(){
valor = document.getElementById("cajaDeTexto").value;
listaSpan += "<span id='"+ valor +"'>"+ valor +"</span> ";
document.getElementById("lista").innerHTML = listaSpan;
//hasta aquí todo bien, es justo aquí donde insertaria una linea con la que me surge la duda. Debajo del ejemplo lo explico.
}, false);
}, false);
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
div{
padding: 20px;
}
span{
background-color: #8dc3ed;
padding: 10px;
display: block;
border-radius: 3px;
margin-bottom: 10px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ejemplo</title>
</head>
<body>
<div style="background-color:#d0d0d0">
Introducir nombre:
<input type="text" name="" value="" id="cajaDeTexto">
<button type="button" name="button" id="boton">Botón</button>
</div>
<div id="lista">
<span>Aquí irán apareciendo los elementos span a medida que sean introducidos mediante la caja de texto y el botón</span>
</div>
</body>
</html>
So far so good, if I inspect the page the span element has been created correctly in the DOM with its corresponding id, in fact you can see it in the example. But then, I want an addEventListener to be added to each of the objects that are created, but obviously I can't put something like this:
document.getElementById(valor).addEventListener("click", function(){
document.getElementById(valor).style.display = "none"; //por ejemplo
}, false)
//tambien he probado: .getElementById("valor") y .getElementById("'"+valor+"'")
What I would like is to be able to print the value of the value variable directly in the js code so that it interprets it like this. I don't know if I'm explaining myself... Maybe I'm getting confused, I'm not sure what the problem is and even less the solution. In short, what I want is that for each of those spans that are created, an addEventListener is created on each of them. Thank you very much for your time!
This is my code actually:
var lista = document.getElementById("lista");
function listaCookies(){ //actualiza la lista de cookies
var cookies = document.cookie.split('; ');
var listaCookies = '';
//bla bla bla
for (var i = 0; i < cookies.length; i++) {
var nombre = cookies[i].substring(0, (cookies[i].indexOf('=')));
var idEliminar = "btn_eliminar_" + nombre;
var close = document.createElement('button');
var span = document.createElement('span');
close.textContent = 'x';
close.className = "eliminar";
span.id = nombre;
span.textContent = cookies[i];
span.appendChild(close);
lista.appendChild(span);
close.addEventListener('click', function(){
//span.remove();
//document.getElementById(nombre).remove();
//close.parentNode.remove();
//this.parentNode.remove();
//HE PROBADO TODO ESTO PERO NADA...
});
}
//bla bla bla
};
What you have to do is use the function
Document#createElement
to create a new element in the DOM tree and be able to associate an event with it; you can also put the attribute directlyonclick
. For reasons of cleanliness and control of the recently created element, I prefer the first option.Update
Because of your comment:
The logic remains the same. The only problem you have in your loop is that you are always referencing the last cookie due to a control variable scope issue. The old option is to use a closure to create a new execution scope where the current cookie is kept so that it can be operated on; the new option is to use the operator
let
instead ofvar
.Example