Huge problem with Span elements in textflow

Ok so i am making a textflow texteditor. I have specified certain spans with at specifik ID to have some special abilities. My problem is that while writing and deleting text in a span in my textflow, the spans are breaking up. Sometimes a new span is created spontanously and devides the text between two spans and sometimes text gets out of the span and into the paragraph. It never happens when adding text but when deleting text it happens sumtimes. I should mention that i have preventet linebreaks with theEnter key.

Here you kan se what is happening. I am just typing text and deleting text ind the same span element - while doing that im getting the html of the textflow:

START:
<HTML><BODY><P ALIGN=“left”><FONT></FONT></P><P ALIGN=“left”><FONT><SPAN id=“HEJ”>ddddd</SPAN><SPAN id=“matbox_0”> ddsfdsfdsdsfsdfdsfdsfsdfsdfsdfdsfff </SPAN>/FONT></P></BODY></HTML>

–> Suddenly i have two SPAN with id= “matbox_0”
<HTML><BODY><P ALIGN=“left”><FONT></FONT></P><P ALIGN=“left”><FONT><SPAN id=“HEJ”>ddddd</SPAN><SPAN id=“matbox_0”> ddsfdsfdsdsfsdfdsfdsfsdfsdfsdfdsf</SPAN>d<SPAN id=“matbox_0”>fsdf </SPAN></FONT></P></BODY></HTML>

// REPARING by merging same-id-spans:
<HTML><BODY><P ALIGN=“left”><FONT></FONT></P><P ALIGN=“left”><FONT><SPAN id=“HEJ”>ddddd</SPAN><SPAN id=“matbox_0”> ddsfdsfdsdsfsdfdsfdsfsdfsdfsdfdsfff </SPAN></FONT></P></BODY></HTML>

–> Text suddenly outside SPAN while i am typing inside the span element:
<HTML><BODY><P ALIGN=“left”><FONT></FONT></P><P ALIGN=“left”><FONT><SPAN id=“HEJ”>ddddd</SPAN><SPAN id=“matbox_0”> ddsfdsfdsdsfsdfdsfdsfsdfsdfsdfdsfff </SPAN>sdfds</FONT></P></BODY></HTML>

What can i do to prevent this ?