Christian Wahl

The contentEditable property

05 Aug 2020 • Christian Wahl

The purpose of this article is to test different HTML elements with the contenteditable attribute, only focusing on the behavior when creating a new line.

Different HTML elements behave differently and depending on the purpose of the editable content this can be an issue. In a case where all line breaks are important, a mix of <div> and <br> elements can mess up the structure of the content.

Documentation:

Testing

Try out the following editors. Write something in the boxes and create new line by hitting enter. My comments are based on the behavior I see in Firefox 79.

Testing <div>
Write here...
<div contenteditable>Write here...</div>

In a <div> a line break will brake up the content in <div> elements creating a <div> for both the content to the left and to the right of the line break.

Testing <p>:

Write here...

<p contenteditable>Write here...</p>

Line breaks will cause a <br> to be created.

Testing <section>:
Write here...
<section contenteditable>Write here...</section>

The <section> element behaves like the <div> element.

Testing <span>:
Write here...
<span contenteditable>Write here...</span>

The <span> element seems to work like the <p> element. The new line will be created with a <br>.

The last two tests already have child elements. The first one is testing a <div> where there is a <p> child element:

Testing <div> with <p>

Write here...

<div contenteditable><p>Write here...</p></div>

Creating a line break in the middle of the <p> element or in the end will end up being two <p> elements.

Testing <div> with <h3>
And the second will test a <div> where there is a <h3> child element:

Write here...

<div contenteditable><h3>Write here...</h3></div>

When the cursor is in the end of a header (<h3>) the next line will be a <div> and if the cursor is in the middle of the header, it will be split in two.

Conclusion

Different elements behave differently when they have the property contenteditable. As I see it there are two options. If the output of the editor is tuned into plain text (innerText) it cound be a good idea to use either the p or <span> element. If you need a more structured output with child elements like headers, paragrafs etc. a block element like <div> should be used.