How to Select All Text in a Contenteditable Div When Clicked?

I have a contenteditable <div> element. I want to select all the text inside it to be selected automatically when clicked. Basically, I want to programmatically select all the text within the <div> whenever it’s clicked.

<div contenteditable="true" id="editable-div">
  Click here to edit the text...
</div>

How can I achieve this functionality using JavaScript or jQuery?

You can achieve this in multiple ways. To select all text within a contenteditable <div>, you can follow the examples below.

With JavaScript

var editableDiv = document.getElementById('editable-div');
    
editableDiv.addEventListener('click', function() {
	var range = document.createRange();
	range.selectNodeContents(editableDiv);
	var selection = window.getSelection();
	selection.removeAllRanges();
	selection.addRange(range);
});

With jQuery

$('#editable-div').click(function() {
	var range = document.createRange();
	range.selectNodeContents(this);
	var selection = window.getSelection();
	selection.removeAllRanges();
	selection.addRange(range);
});

Here is a simple but little bit different example:

<div contenteditable="true" id="editable-div" onclick="document.execCommand('selectAll',false,null)">
  Click here to edit the text...
</div>

Use whatever suits your needs.