Search code examples
javascriptjqueryhtmlcontenteditable

Type content inside contenteditable, outside child element


I have a contenteditable div:

<div contenteditable="true"><strong>Hi there</strong></div>

When I type something inside it, all the texts are bold. I checked using Inspect Element and it seems that everything typed goes inside "strong" tag but I want it to be outside of it, inside div tag. How do I fix this problem?

div {
  height: 250px;
  }
<div contenteditable="true"><strong>Hi there</strong></div>


Solution

  • You can fix that simply by setting contenteditable="false" on the <strong> element.

    div {
      height: 250px;
    }
    <div contenteditable="true"><strong contenteditable="false">Hi there</strong></div>

    You'll still be able to delete the "Hi there" but not edit it directly.

    Alternatively, you can structure your HTML like so:

    div {
      height: 250px;
    }
    p {
      display: inline-block;
    }
    <div><strong>Hi there</strong> <p contenteditable="true"></p></div>