How can I select text inside a div element when I click on it? jQuery there no standard method in jQuery for such an action?
|
2 answers
There is a specification ( Selection API ) that describes how JavaScript code can interact with the selection of text on a page.
Without going into details, I’ll show you how to use this API to select the contents of the <div> when you click without using jQuery:
document.getElementById('select-target').addEventListener('click', function() { var r = document.createRange(); r.selectNode(this); document.getSelection().addRange(r); }); Here is a JSFiddle with an example.
Comment:
If you need to write the maximum cross-browser code, you can use libraries that wrap the Selection API, for example, Rangy .
|
<script> function selectText(containerid) { if (document.selection) { // IE var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerid)); range.select(); } else if (window.getSelection) { var range = document.createRange(); range.selectNode(document.getElementById(containerid)); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); } } </script> <div id="example" onclick="selectText('example')">Hello This div content have to be select.</div> |