The contenteditable attribute is used to edit the text in the browser. If the contenteditable is specified as true then the content can be edited or if it’s set as false then the content in the browser cannot be editable. In the modern web, most of the websites offer an option to the user for editing the values in a web page and save it to the session or local storage for the future use. However, there is no built-in editor support for this functionality till HTML4, in HTML5 contenteditable makes it easy for the web designers to have edit form within the page itself.
Defined in HTML5 spec as:
contenteditableattribute is an enumerated attribute whose keywords are the empty string, true, and false. The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the inherit state, which is the missing value default (and the invalid value default). ( Reference )
Syntax Of <contenteditable> Attibute
<element contenteditable= "true /false">;
contenteditable attribute can have three states:
- contenteditable=”” or contenteditable=”true”: It means that the content can be edited.
- contenteditable=”false”: It means the content cannot be edited.
- contenteditable=”inherit”: It means the element is editable if its immediate parent element is editable. This is the default behaviour.
HTML5 Contenteditable Example
Following example demostrates all the above three states:
<!DOCTYPE html> <html> <head> <title> Contenteditable Attribute</title> </head> <body> <div id="editor-1" contenteditable=""> <p>You can edit me as <i>contenteditable</i> is set to <i>""</i>. </p> </div> <div id="editor-2" contenteditable="true"> <p>You can edit me as <i>contenteditable</i> is set to <i>true</i>. </p> </div> <div id="editor-3" contenteditable="false"> <p>You cannot edit me as <i>contenteditable</i> is set to <i>false</i>. </p> </div> <div id="editor-4" contenteditable="true"> <p>You cannot edit me as <i>contenteditable</i> is set to <i>true</i>. </p> <div id="editor-5"> <p>You cannot still edit me as i'v inherited the parent properties. </p> </div> </div> </body> </html>
Here you can see that we are testing all the three states of the contenteditable attribute.
Example Application Test
- Save the file as contenteditable_example in your system.
- Just open the file in the browser, you will see the below picture in the browser. Note that the browser must support HTML5 specification.
When the execution process is completed successfully we will get the following output. In the below screenshot the highlighted or border line is editable text where cursor is pointed.