Sometimes, we want to select all div text with a single mouse click with JavaScript.
In this article, we’ll look at how to select all div text with a single mouse click with JavaScript.
Use the document.body.createTextRange or document.createRange Method
We can use the document.body.createTextRange
or document.createRange
method to create a selection.
For instance, if we have the following HTML:
<div id="selectable">http://example.com/page.htm</div>
Then we can write the following code:
const selectable = document.getElementById('selectable')
selectable.addEventListener('click', () => {
if (document.selection) {
const range = document.body.createTextRange();
range.moveToElementText(selectable);
range.select();
} else if (window.getSelection) {
const range = document.createRange();
range.selectNode(selectable);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
})
to add a click listener to the div and select the text in the div when we click on it.
To do this, we call getElementById
to select the div.
Then we call addEventListener
with 'click'
to add a click listener to it.
In the callback, we call documebnt.create.createTextRange
method to create a selection if document.selection
is defined.
This is defined if the code is run in IE.
Then we call moveToElementText
to move the cursor to the text content.
Then we call select
to highlight all the text.
On all other browsers, we call document.createRange
to create the selection.
Then we call selectNode
with the element with the content that we want to create the selection.
Then we call removeAllRanges
to remove all the existing selected items.
And finally, we call addRange
with the range
to select the selection range we created.
Now when we click on the div text, the text will be selected.
Conclusion
We can select all the text when we click on the div text by creating a selection object and then select the text.