Search code examples
htmlcontenteditable

contentEditable does not wrap first line in tags


I have a div with the attribute contentEditable set.

The trouble I am having is that the first line I type does not get wrapped in tags, but the subsequent lines do.

So typing:

qwerty
zxcv
asdfg

Results in:

<div class="editable" contentEditable="true">
    qwerty
    <div>zxcv</div>
    <div>asdfg</div>
</div>

So I need the qwerty line to become <div>qwerty</div>


Solution

  • If you start with an element that contains a div inside it like this:

    <div class="editable" contentEditable="true"> <div></div> </div>

    the first line you type will end up being wraped in a div.

    UPDATE:

    This is browser specific. While it did work in most browsers at the time the question was posted, it does not necessarily work anymore in the latest browser version. Best way to tell is to just test it.