I am using Angular 13 with a pipe to reformat text in a contenteditable div. Everything is working fine until the innerHtml is replaced with the new code. The attributes from the last child node (a span tag) are appended to the inside of the closing span tag. I have no idea why this is happening.
I'm using TypeScript, with Angular 13, on Chromium (MS Edge) v97.0.1072.76 and Firefox v95.0.
Here's an example:
reformatContent(event: Event) {
const el = (event.target as HTMLElement);
const originalHtml = el.innerHTML;
console.log(originalHtml); // "Some text <span id="someTextId" class="someTextClass">More Text</span>
const newHtml = this.reformatText(originalHtml);
console.log(newHtml); // "Some text <span id="someTextId" class="someTextClass someNewClass">More Text</span> <-- this is ok, what I expected.
el.innerHTML= newHtml;
console.log(el.innerHTML); // "Some text <span id="someTextId" class="someTextClass someNewClass">More Text</span id="someTextId" class="someTextClass someNewClass"> <-- why is this happening???
}
I just want to be clear that the originalHtml includes the close </span> tag. So I don't think the browser is trying to close the tag.
Edit for typo.
Edit 2: I updated the original code for typos and to make it more clear how I was getting the innerHTML. I didn't think that was where the problem was, but apparently that's it, because this works:
reformatContent(event: Event) {
const e = (event.target as HTMLElement);
const el = document.getElementById(e.id);
const originalHtml = el.innerHTML;
console.log(originalHtml); // "Some text <span id="someTextId" class="someTextClass">More Text</span>
const newHtml = this.reformatText(originalHtml);
console.log(newHtml); // "Some text <span id="someTextId" class="someTextClass someNewClass">More Text</span> <-- this is ok, what I expected.
el.innerHTML= newHtml;
console.log(el.innerHTML); // "Some text <span id="someTextId" class="someTextClass someNewClass">More Text</span> <-- now it works
}
I don't understand why the original way of getting the element caused this problem. I fixed it, but I'd really like to understand what's happening here.
What is reformatText function?
this.reformatText(originalHtml)
This function is changing your span and your bug is from here.
You might say that your result are right but you are using console.log on an invalid variable (originalHtml)
What is and where is originalHtml?
But generally what I know, your problem is because of this line:
const newHtml = this.reformatText(originalHtml);