Create addEventListener in a span whose id is contained in a variable

3

good morning. First of all I apologize for how unclear the title is, I have not been able to 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 is my doubt and avoid complicating us unnecessarily by trying to resolve my doubt in my code.

The example is as follows: On the page there is an input where to write and a button. Pressing the button executes the following function: - Using an innerHTML, create an html element (a span) with the value of the input as id. -In addition I want you to create an addEventListener on that object, but of course, the id of that span I only have it stored in the variable and I do not know how to use the variable to refer to each of the span 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 element span has been created correctly in the DOM with its corresponding id, in fact you can see it in the example. But then, I want to add an addEventListener to each of the objects that are created but obviously I can not 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 variable value directly in the js code so that it can be interpreted that way. I do not know if I explain myself ... Maybe I'm confusing myself, I'm not sure what the problem is, let alone the solution. In short, what I want is that for each one of those spans that are created, an addEventListener is created on each one 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

};
    
asked by Adrià Fàbrega 21.02.2017 в 16:19
source

1 answer

2

What you should do is use the Document#createElement function to create a new one element in the DOM tree and be able to associate an event with it; you can also put the onclick attribute directly. For reasons of cleanliness and control of the newly created element, I prefer the first option.

Update

Because of your comment:

  

The close button does not work in my case, because those values are obtained by slicing with .split() a text string (document.cookie) and with a loop for I have them drawn spans corresponding to each of the elements of the resulting array.

The logic remains the same. The only problem you have in your loop is that you are always referring to the last cookie due to a problem of scope of the control variable. The old option is to use a closure to create a new scope of execution where keep the current cookie to be able to operate with it; the new option is to use the operator let instead of var .

Example

var mycookies = 'c1=Cookie1; c2=Cookie2; c3=Cookie3; c4=Cookie4';

document.addEventListener("DOMContentLoaded", function() {
  var listaSpan = document.getElementById('lista');
  var input = document.getElementById('cajaDeTexto');
  var btn = document.getElementById('boton');
  var cookies = mycookies.split('; ');
  
  
  for (var i=0; i<cookies.length; i++) {
    var cookie = cookies[i];
    var cookieName = cookie.substring(0, cookie.indexOf('='));
    var cookieValue = cookie.substring(cookie.indexOf('=') + 1);
    
  	(function (name, value) {
    	var span = document.createElement('span');
      var close = document.createElement('button');
      close.textContent = 'x';
      span.id = name;
      span.textContent = value;
      span.appendChild(close);
      close.addEventListener('click', function() {
        span.remove();
      });
      // aquí se agrega el span al árbol
      listaSpan.appendChild(span);
    })(cookieName, cookieValue);
  }
});
* {
  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;
}

span button {
  background-color: #eee;
  border: none;
  border-radius: 100%;
  cursor: pointer;
  float: right;
  font-size: 13px;
  height: 15px;
  width: 15px;
}
<div id="lista">
  <span style="background-color: gold; text-align: center">
    Lista de cookies
  </span>
</div>
    
answered by 21.02.2017 / 16:33
source