Skip to content

Instantly share code, notes, and snippets.

@tcr
Created October 26, 2011 23:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcr/1318279 to your computer and use it in GitHub Desktop.
Save tcr/1318279 to your computer and use it in GitHub Desktop.
How do different browsers handle empty paragraphs/blocks using contentEditable?
<!-- most modern browsers -->
<p><br></p>
<!-- ie9 -->
<p></p>
<!-- ie7-8 -->
<script>
document.body.appendChild(document.createElement('p'))
</script>

Empty paragraphs would be those which have no editable content, but are still selectable via cursor and let content be added to them.

From my tests:

  1. 'Modern' browsers (Chrome/Firefox) -- Adds a
    as the last element. This
    can't be edited/selected, but it keeps the tag artificially "open" whenever there's no other content in it. Can be written using HTML.

  2. IE9 -- Empty paragraphs can be fully empty and still editable.

  3. IE7--8 -- Empty paragraphs are fully empty and still editable. However, innerHTML reads as though there was an   in the paragraph (there's not). Also, manually writing <p>&nbsp;</p> in HTML actually adds an editable space, but <p></p> isn't editable! Turns out this works only if you add an empty paragraph via DOM methods (with no inner nbsp)

["innerhtml","contenteditable","space","html","dom","ie","browers","compatibility"]
@lerouxb
Copy link

lerouxb commented Jul 20, 2012

By the way, it appears that chrome (I haven't checked the other browsers, but this probably applies to all modern webkit browsers) allows you to place the cursor (and dynamically created ranges and selections) inside an empty p tag in a contenteditable if you give it a min-height. Empty p tags created by the browser when pressing enter at the end of a paragraph while editing to create a new paragraph somehow works (and without any extra br tags or anything), but empty p tags that you add via code straight to the contenteditable doesn't. The min-height trick helps with that.

What I find odd is that this affects behavior from the user's perspective (you can now click on it because it takes up space) and also from the javascript/dom perspective. So this code suddenly works whereas without the min-height CSS it is just ignored:

var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(newEmptyParagraph);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);

It is almost like it triggers some hidden "hasLayout" style condition ;)

I tend to style empty tags while editing anyway so that you don't end up with invisible things that you can't focus or remove.

@shenyan008
Copy link

maybe a bug in webkit since 2005
https://bugs.webkit.org/show_bug.cgi?id=4003

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment