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:

<!DOCTYPE html>

<html lang="en">

<head>

<style>

.divclass {

background: #3B505F;

height: auto;

width:345px;

border-radius: 8px;

padding:150px;

font-size:16px;

color:#fff;

}

</style>

 

</head>

<body>

<h1>A demo of HTML contentEditable</h1>

<div contentEditable="true" class="divclass">Click here and edit text</div>

</body>

</html>

 

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:

<!DOCTYPE html>

<html lang="en">

<head>

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

<style>

.h1cls {

background: #3B505F;

height: auto;

width:310px;

padding:5px;

font-size:16px;

color:#fff;

margin:20px;

}

</style>

 

</head>

<body>

<h1>A demo of HTML contentEditable</h1>

<h1 contentEditable="true" class="h1cls" id="contentEditabledemo1">Click on this heading to edit text</h1>

 

<button class="btn btn-danger btn-lg" onclick="showeditable()">Display H1 text</button>

 

<script type="text/javascript">

function showeditable(){

var var_edittext = document.getElementById("contentEditabledemo1").innerHTML;

alert ("The div text is: " + var_edittext);

}

</script>

</body>

</html>

 

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.