How to change div contenteditable from true to false

Theng Ming picture Theng Ming · Jun 8, 2013 · Viewed 29.3k times · Source

I got a page which let user change the text inside div and save the html code into a database, however when I display back the html code I want to change the div contenteditable to false. Is there any way???

Answer

squirly picture squirly · Jun 8, 2013

Since you have 5 elements with contenteditable, try giving them IDs to simplify access.

The following code deactivates the 5 contentediable elements:

var editable_elements = document.querySelectorAll("[contenteditable=true]");
editable_elements[0].setAttribute("contenteditable", false);
editable_elements[1].setAttribute("contenteditable", false);
editable_elements[2].setAttribute("contenteditable", false);
editable_elements[3].setAttribute("contenteditable", false);
editable_elements[4].setAttribute("contenteditable", false);

Demo

Or you can you a loop

var editable_elements = document.querySelectorAll("[contenteditable=true]");
for(var i=0; i<editable_elements.length; i++)
    editable_elements[i].setAttribute("contenteditable", false);