Add attribute contentEditable to P element using JavaScript and jQuery

← PrevNext →

I am sharing two different examples here in this post showing how to add the contentEditable attribute or property to a <p> element using JavaScript and jQuery.

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>
Try it

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>
Try it

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>
Try it

I am using the jQuery .attr() method to assign values to the contentEditable attribute. In-addition, you can use the .prop() method too.

← PreviousNext →