Home >Web Front-end >CSS Tutorial >How Can I Select All Text Within a DIV Element with a Single Click?
Selecting All Text in a DIV with a Single Click
Allowing users to effortlessly select all text within a DIV element can enhance productivity and user experience. This can be achieved by using event handlers, which enable the execution of specific actions in response to mouse clicks.
Consider the following example, where we have a DIV with the ID "selectable" containing a URL:
<div>
To automatically select the URL text when a user clicks on the DIV, we can use the following JavaScript code:
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); } }
To utilize this functionality, add the following HTML code to your page:
<div>
This code will ensure that when a user clicks on the DIV with the ID "selectable," the entire URL text will be selected, enabling easy dragging, copying, and pasting of the text.
The above is the detailed content of How Can I Select All Text Within a DIV Element with a Single Click?. For more information, please follow other related articles on the PHP Chinese website!