Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda