Add attribute contentEditable using JavaScript
Let us assume, I have <p> element on my web page. I want to make it editable at runtime or dynamically.
<p id='theEle'> Some text here … </p>
The JavaScript code:
<script>
document.getElementById('theEle).contentEditable = 'true';
</script>
Simple, isn’t it. It’s a one-line code. You can set the value to true or false. The contentEditable attribute takes a Boolean value.
Now, let’s see how we can toggle the attribute value (setting it true or false) using JavaScript.
<p id='theEle' contentEditable></p> <input type='button' onclick='setP()' value='click to make P editable' id='bt' /> <script> let setP = () => { let val = document.getElementById('theEle'); if (val.contentEditable === 'true') document.getElementById('theEle').contentEditable = 'false'; else document.getElementById('theEle').contentEditable = 'true'; } </script>
Or, you can use the Logical Operators.
let setP = () => { let val = document.getElementById('theEle'); val.contentEditable === 'true' ? document.getElementById('theEle').contentEditable = 'false' : document.getElementById('theEle').contentEditable = 'true'; }
Add attribute contentEditable using jQuery
Here’s how you can add the contentEditable attribute to a <p> element using jQuery.
<body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p id='theEle'></p> <input type='button' onclick='setP()' value='Click it' id='bt' /> </body> <script> $(document).ready(function () { $('#bt').click(function () { $('#theEle') .attr('contenteditable', 'true') .focus(); }); }); </script> </html>
I am using the jQuery .attr() method to assign values to the contentEditable attribute. In-addition, you can use the .prop() method too.