I would like to replace non-img elements inside a contenteditable with their text. However, I want to preserve any img elements, including those nested inside other elements. In other words:
Given input such as:
<div><span>Foo <strong>Bar <img src="blah.png"></strong> and more text <img src="another.png"></span> With some other text <img src="yetmore.png"></div>
I would like to produce:
Foo Bar <img src="blah.png"> and more text <img src="another.png"> With some other text <img src="yetmore.png">
As this is a contenteditable, I don’t want to use innerHTML reading/writing, as that will lose cursor position and the like (restoring it is Hard, because you end up with a different DOM tree so your selection nodes get lost).
Is my best bet to just iterate over the tree and manually split and concatenate text nodes and so on? I’m hoping there’s a better way, or a library that can already do things like this…
Make a shallow clone of the root element. Walk down the original’s element tree, collecting text. When you come across an img element, add the text gathered so far as a text node that is a child of the clone. Append the img. Start collecting text again.
Keep going until you get to the end, then replace the original root element in the document with the clone.
Edit
Something like: