3

I have seen many questions related to div tag with contenteditable attribute, but my problem is a bit different.

I don't care whether hitting enter and adding new lines adds <div> or <br>, but when I select all the text by hitting CTRL + A and then clearing it by pressing DEL or BACKSPACE, it adds additional <br>. But when text is only in one line, selecting and clearing it leaves nothing.

How can I avoid the situation when clearing many lines of text adds additional <br> tag?

TheOpti
  • 1,561
  • 2
  • 19
  • 35

1 Answers1

2

ContentEditable is managed by the the browser to inject formatting tags as it sees fit; so, if you want plain text, you may be better of with a textarea input. If that is not a viable option and/or you want all the other formatting, then you could use a javascript or jQuery listener to check innerHTML on each keystroke to see if it contains the rogue br tag and eliminate it.

$("div").on("keyup", function () {
  if (this.innerHTML === "<br>") {
    this.innerHTML = "";
  }
});
Nosajimiki
  • 978
  • 1
  • 8
  • 15
  • This solution will work only in Chrome. In Edge, deleting multiple lines of text leaves the last line of this text. – TheOpti Aug 08 '17 at 21:16
  • interesting... it may be an issue with the order in which edge executes passed and native functions. Not sure if this will work, but try using a function that does not test for keystrokes: like make something that checks for the
    tag every 500ms. You might be able to get around the browser's own listener that way.
    – Nosajimiki Aug 08 '17 at 21:21