I’ve been experiencing a very strange behavior inside the contenteditable div-element. If I press enter a new div with a span tag is created. My goal is to assign some event listeners to the newly created span element.
Therefore, I created a function that is executed on the keyup-event. Inside this function I check if the span elements have an id or the attribute eventListenersAdded.
If I press enter the first time the span doesn’t have this attribute the event listeners and this attribute are added to the new span. Everything okay.
But now if I press enter the second time a new span tag is added with the same properties as the last created span tag. So this span tag has the attribute eventListenersAdded already, before I executed the function and without adding this attribute to the new span.
This is the log after pressing enter the first time (everything fine):
This is the log after pressing enter the second time:
The second created span tag already have this attribute without adding it to this.
This is the code:
let target = event.target as HTMLElement;
let spans = target.getElementsByTagName('span');
for (let i = 0; i < spans.length; i++) {
if (spans[i].getAttribute('eventListenerAdded')) continue;
spans[i].setAttribute('eventListenerAdded', 'true');
}
How is this possible?