HTML5 contentEditable to make div, H1 or other elements editable

How to make display text elements editable?

By using HTML 5 contentEditable attribute, you may make the display element’s text (paragraph, span, headings etc.) editable in web pages. Although, this is generally not required, however in some cases may be!

By using the contentEditable and setting its value as true, you may make div, paragraph, headings etc as editable.

A demo of making a div element editable

In this example, I have created a div element with a little CSS. Click inside the div and enter the text to see how it works:

HTML contentEditable

See online demo and code

The complete code used in the demo:

 

You can see, the value of the contentEditable attribute is set as true for making the text editable.

A demo of getting editable element text by using JavaScript

If you are making the text editable for the display text elements like div, span or headings then there must be some reason for that. One of the reason could be fetching text and performing some action based on that.

So in this example, I am just going next step and accessing the editable element text by using the JavaScript. The element is an H1 heading.

HTML contentEditable h1

See online demo and code

The complete code of demo:

 

As you run this demo and edit the text in the heading and click on the button, it will display the complete text in the div tag in an alert.

This is done by using the getElementById(“contentEditabledemo1”).innerHTML where contentEditabledemo1 is the ID of the <h1> tag.

Similarly, you may use the jQuery code or some other scripting for getting the text and performing some action after making the display fields as editable.