'Script only changing document.body.contentEditable to false and not true

javascript:if(document.body.contentEditable == false){document.body.contentEditable = true;}else{document.body.contentEditable = false;} void 0;

it appears that all it does is make it false.



Solution 1:[1]

The reason it is always changing it to false is primarily because document.body.contentEditable is going to be a string (i.e., "true", "false", "inherit"). Your code just needs to include quotes around true and false in your conditional for it to work as intended:

javascript:if(document.body.contentEditable == "false"){document.body.contentEditable = "true";}else{document.body.contentEditable = "false";} void 0;

Solution 2:[2]

Since contenteditable is an element attribute, it is best read, set, or changed, using the .getAttribute and .setAttribute properties of the element's object.

The snippet shows the syntax used to read and set the attribute, using a working example where a button toggles editability of a paragraph element.

let editBox = document.getElementById("edit-field");

document.getElementsByTagName('button')[0].addEventListener('click', event =>{

    if (editBox.getAttribute("contenteditable")=="true") {
    editBox.setAttribute("contenteditable", "false");
    console.log("switched to not editable");
  } else {
    editBox.setAttribute("contenteditable", "true");
    console.log("switched to editable");
  }
}) // end button click;
#edit-field {
  width: 300px;
  height: 100px;
  background: yellow;
}
<p id="edit-field" contenteditable="false"> I am editable (sometimes)</p>
<button>toggle editability </button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 phentnil
Solution 2 Dave Pritlove