Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
Event listeners disappear after adding new element

My goal is the following: there is a div with an editable span inside, when a dot is typed inside the span I want to add a new span adyacent to it, focus the new span and continue writing in that one, which should have the same behaviour.

The behaviour I describe actually works, but every time a new span is added, the previous loses every event listener I had added.

The body of my html file looks like this

<body>
    <div id="search">
        <span class="tag">person</span>.
    </div>
    <script src="myscript.js"></script>
</body>

where myscript.js creates a first span (span1) inside #search and then adds the folowing event listeners


function createTag(event) {
    if (event.key == '.') {
        let color = search.childElementCount;
        let span = document.createElement('span');
        span.setAttribute('style', 'color:' + palette[color]);
        span.className = 'tag';
        span.contentEditable = true;
        search.innerHTML = search.innerHTML + '.';
        search.appendChild(span)
        span.addEventListener('keyup', createTag);
        span.addEventListener('blur', deleteTag);
        span.focus()
    };
};

function deleteTag() {
    if (this.innerText.length == 0 && search.childElementCount > 2){
        search.removeChild(this);
    }
}

span1.addEventListener('keyup', createTag);
span1.addEventListener('blur', deleteTag);

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda