60

Do you know how to make a <div> editable with JavaScript? I'm looking for cross-browser solution.

Something similar to a rich text area, but that uses an editable <iframe>. I need something similar for a <div>.
I don't want to use a replacement textbox.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Cristian Toma
  • 5,662
  • 2
  • 36
  • 43

4 Answers4

84

I found out how.

You use the contentEditable property of the DOMElement, like so

<div onClick="this.contentEditable='true';">
    lorem ipsum dolor lorem ipsum dolorlorem ipsum dolor
</div>
Cristian Toma
  • 5,662
  • 2
  • 36
  • 43
  • 2
    Yes my friend, it really does work in Internet Explorer 6 ! Here is more info on this subject and the risks of using it in older versions of Internet Explorer. http://stackoverflow.com/questions/491790/risk-of-usingcontenteditable-in-ie Thank you. – Cristian Toma Jul 27 '09 at 21:46
  • 11
    Why not just set the attribute `contenteditable=true`, without the `onClick`? Or did/does IE not support that when this was answered? – Blazemonger Apr 17 '13 at 20:16
  • It's actually property of HTMLElement. See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/contentEditable – Michał Perłakowski Jan 02 '16 at 18:05
15

You can do this in pure HTML

<div class="editable" contenteditable="true">
    Editable text...
</div>

Hope this helps!

André Figueira
  • 6,048
  • 14
  • 48
  • 62
  • OP wants to do this with JavaScript. – Michał Perłakowski Jan 02 '16 at 10:43
  • 4
    @Gothdo Actually this is the way to do this, no need of JS. Using the accepted answer, you have to click **twice** on the div to edit it the first time. Here the div appears as an ordinary div until you click it where it becomes editable. – Déjà vu Dec 05 '16 at 02:07
6

Set contentEditable property of the element to "true":

element.contentEditable = "true";

See also:

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
-2
How about his: 

Make a hidden "textArea" , and upon selecting(clicking or Hover) the div , hide the Div and Show the textArea .

Posto
  • 7,362
  • 7
  • 44
  • 61
  • 30
    That's exactly what I don't want to do. Thanks. – Cristian Toma Jul 27 '09 at 14:59
  • It was way back, but as still getting some -down vote, IMHO "I don't want to use a replacement textbox." Was not added when I posted this possible alternative . – Posto Jan 11 '22 at 04:54