5

I have a div

<div contentEditable="true">
    <h1> My headline</h1>
</div>

If i am editing the text inside the <h1> tag, and press return, it adds a new div under, instead of the normal paragraph tag it usually inserts when entering return

Making it:

<div contentEditable="true">
    <h1> My headline edited</h1>
    <div> i tapped return</div>
</div>

What i really want is

<div contentEditable="true">
    <h1> My headline edited</h1>
    <p> i tapped return</p>
    <p> return again</p>
</div>

Whats strange is that usually when you write somewhere and press return it adds a new <p>, but just not when editing <h1>. Is it possible to fix this with Javascript/Jquery/Html5?

I am using Safari on an iOS-device

bogen
  • 9,954
  • 9
  • 50
  • 89
  • Look at this could be similar problem: http://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome – Piotr Czarnecki Aug 31 '15 at 07:49
  • I don't want them inside, i want it to add them after, like when you edit another

    – bogen Aug 31 '15 at 07:49
  • Yo should capture ENTER, and attach your own content. What comes to a "normal tag", there's no normal tag (`p` in IE, `div` in most of other browsers, but also possible `br`s etc.). – Teemu Aug 31 '15 at 08:09
  • "usually when you write somewhere and press return it adds a new `

    `, but just not when editing `

    `" This is because h1...h6 elements aren't supposed to contain `

    ` tags; according to the HTML spec they can only contain "Phrasing content" which is these tags only: https://html.spec.whatwg.org/multipage/dom.html#phrasing-content

    – Daniel Beck May 20 '17 at 20:45

1 Answers1

3

Adding a format blocker inside onkeyup with p will force the contenteditable (div) to add <p> tag on return.

editable.onkeyup = (e)=> {
    e = e || window.event
    if (e.keyCode === 13)
        document.execCommand('formatBlock', false, 'p');
}
Nilesh Singh
  • 1,750
  • 1
  • 18
  • 30