Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!