Home > Web Front-end > CSS Tutorial > How Can I Select All Text Within a DIV Element with a Single Click?

How Can I Select All Text Within a DIV Element with a Single Click?

Susan Sarandon
Release: 2024-12-13 21:22:15
Original
643 people have browsed it

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>
Copy after login
Copy after login

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);
  }
}
Copy after login

To utilize this functionality, add the following HTML code to your page:

<div>
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template