I confirmed contenteditable's behavior to better understand how it works.
Before you read...
You must know
Text node
Suppose we have the following HTML with no element but a text node inside a contenteditable element.
<div contenteditable="true">
This is a text node.(caret)
</div>
Depending on your browser, there are 2 patterns after you delete the whole text by Backspace.
Chrome and Edge
Nither text node nor element is created.
<div contenteditable="true">
(caret)
</div>
Safari and Firefox
<br>
is generated and you CANNOT delete it.
<div contenteditable="true">
(caret)<br>
</div>
Block-level element
Suppose we have a p element inside a contenteditable element.
<div contenteditable="true">
<p>This is a p element.(caret)</p>
</div>
Chrome, Safari and Edge
<br>
is created inside the p element after you delete the whole text.
<div contenteditable="true">
<p>(caret)<br></p>
</div>
Then the element is gone after you press one more Backspace.
<div contenteditable="true">
(caret)
</div>
This behavior is the same for other block-level elements, such as h1 to h6, div and so on.
Firefox
Firefox is strange. It inserts <br>
when a letter before a space is deleted like below.
<div contenteditable="true">
<p>A p element is (caret)<br></p>
</div>
The <br>
remains until you reach the head of the line, and when you delete the whole text, it becomes the same state as the other browsers in the end.
<div contenteditable="true">
<p>(caret)<br></p>
</div>
Then the element is gone after you press one more Backspace.
<div contenteditable="true">
(caret)
</div>
List
I'll cover ul and ol elements as their behavior is different from other block-level elements.
<div contenteditable="true">
<ul>
<li>Item 1(caret)</li>
</ul>
</div>
After you delete the whole text, the li element looks the same as other block-level elements.
<div contenteditable="true">
<ul>
<li>(caret)<br></li>
</ul>
</div>
However it goes differently after you press one more Backspace.
Chrome, Safari and Edge
<div><br></div>
is created.
<div contenteditable="true">
<div>(caret)<br></div>
</div>
And <div><br></div>
will be gone by one more Backspace.
<div contenteditable="true">
(caret)
</div>
Firefox
When it comes to Firefox, all the elements are gone. It doesn't create <div><br></div>
.
<div contenteditable="true">
(caret)
</div>
Inline element
<div contenteditable="true">
<span>This is a span element.(caret)</span>
</div>
Chrome, Safari and Edge
When you delete the whole text, the span element is gone and <br>
is inserted.
<div contenteditable="true">
(caret)<br>
</div>
Firefox
Firefox inserts <br>
again when a letter before a space is deleted.
<div contenteditable="true">
<span>A p element is (caret)<br></span>
</div>
The <br>
remains until you reach the head of the line and you CANNOT delete the <span><br></span>
this time. What in the world is that?
<div contenteditable="true">
<span>(caret)<br></span>
</div>
Top comments (0)