i have a contentediable div. I build the possibility, to upload image from my computer directly inside the contentediable div. Everything until here works perfect. I wrapped the image inside another div, so i can add a icon to the image (for the possibility to delete the image).
The icon is a span
element.
I insert the image into the contentediable div like this:
document.execCommand(insertHTML, null, htmlString);
This is the htmlString i add:
<div class="wrapper"><div class="icon-wrapper"><span contenteditable="false" class="material-symbols-outlined">close</span></div><img src="IMAGE_URL" ></div>
My icon is inside the span
attribute. In Browser its looks like this:
view image
Everything until here is correct.
But the problem is, that the icon is also editable. If i click the icon, i can change the text of this icon and because of this, the icon disappers because its only shows up, when the text inside the span
attribute is close
.
here is an image of the editable span (icon)
In my htmlString i added the attribute contentediable="false"
to the span
element but its not working.
If open the development tools in browser and inspect the html rendered, i can see, that the contenteditable
attribute is not set.
This is the rendered html from the developer tools of chrome:
<div class="wrapper"><div class="icon-wrapper"><span class="material-symbols-outlined">close</span></div><img src="IMAGE_URL"></div>
I think its a problem with document.execCommand
.
I added contentediable="false"
attribute to the span element inside the htmlString because i hoped, this should fix this problem. But i dont know why its getting ignored. When i inspect the element in the browser the arribute is not set.
I tried to add the attribute contentediable="false"
to the parent (icon-wrapper). But same problem here.
When i edit the html directly in the browser with the developer-tools and add there the contentediable attribute, its works like expected. But in my opinion it should work with the attribute set in the htmlString i gave to the function document.execCommand
.
I didnt find any solution for this problem in the internet.
Try setting the contenteditable
attribute after the HTML has been inserted, like this:
// Assuming htmlString contains your HTML
var htmlString = '<div class="wrapper"><div class="icon-wrapper"><span class="material-symbols-outlined">close</span></div><img src="IMAGE_URL"></div>';
// Insert the HTML
document.execCommand('insertHTML', null, htmlString);
// Set contenteditable="false" for the span element
var spanElement = document.querySelector('.icon-wrapper span');
spanElement.setAttribute('contenteditable', 'false');