I am trying to create a button with a function that will enable or disable contenteditable
for all <div>
's however I get that contentEditable
is not a function, anyone know why?
function contentEditable() {
var x = document.getElementsByClassName("editable");
if ($(this).attr("contentEditable") == "true") {
console.log=(hello);
x.setAttribute('contentEditable', 'true');
button.innerHTML = "Enable content of p to be editable!";
} else {
x.setAttribute('contentEditable', 'false');
button.innerHTML = "Disable content of p to be editable!";
}
}
<button onclick="contentEditable(this);" id="contentEdit" class="btn btn-primary form-control margin">Edit Text</button>
So many issues I'll just post an annotated example.
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<!-- make sure contenteditable is set to false initially -->
<div class="editable" contenteditable="false">some text 1</div>
<div class="editable" contenteditable="false">some text 2</div>
<div class="editable" contenteditable="false">some text 3</div>
<button id="contentEdit" class="btn btn-primary form-control margin">Edit Text</button>
<script>
var button = document.querySelector('#contentEdit');
var contentEditable = function contentEditable() {
// getElementsByClassName returns a nodelist,so we ahve to cast it to an array, or use a basic for-loop.
var editables = Array.prototype.slice.call(document.getElementsByClassName("editable"));
editables.forEach(function( x ) {
// We want to check the <div> tag for editable, not the button
// the correct attribute is lowercase contenteditable
if (x.getAttribute("contenteditable") === 'false') {
// fixed syntax
console.log("hello");
x.setAttribute('contenteditable', 'true');
// swicthed around Disable and Enable in the strings to make the logic correct.
button.innerHTML = "Disable content of p to be editable!";
} else {
x.setAttribute('contenteditable', 'false');
button.innerHTML = "Enable content of p to be editable!";
}
});
};
button.addEventListener("click", contentEditable);
</script>
</body>
</html>