Making Div content to be Editable

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts:48

Making Div content to be Editable

Can I make the content of a html div to be editable?
For example I have the following code:

Code: Select all

<div id="edit1">Content that can be edited.</div>
<button id="show">Show</button>
<script>
document.getElementById('show').addEventListener('click', function(){
  var cnt = document.getElementById('edit1').innerHTML;
  alert(cnt);
});
</script>
I want to can edit the content of the "#edit1" Div, then, when I click on the button (Show) to alert the new content.

MarPlo Posts:186
To make the content of a html element to be editable, just add the: contentEditable="true" attribute in that tag. It can be used in almost all HTML elements.

Code: Select all

<div id="edit1" contentEditable="true">Click here and edit this content: https://coursesweb.net/<br>Then click on the button.</div>
<button id="show">Show</button>
<script>
document.getElementById('show').addEventListener('click', function(){
  var cnt = document.getElementById('edit1').innerHTML;
  alert(cnt);
});
</script>
Demo:
Click here and edit this content: https://coursesweb.net/
Then click on the button.

- If you want to add the "contentEditable" property dinamically with JavaScript, use this code:

Code: Select all

document.getElementById('elm_id').setAttribute('contentEditable', 'true');