Home > Web Front-end > CSS Tutorial > How to Select All Text Within a DIV with One Click?

How to Select All Text Within a DIV with One Click?

Patricia Arquette
Release: 2024-12-11 10:22:21
Original
766 people have browsed it

How to Select All Text Within a DIV with One Click?

Select DIV Text Effortlessly with a Single Mouse Click

For quick and convenient text manipulation, it's often desirable to highlight and select the entire contents of a DIV tag. This allows users to easily perform actions such as dragging selected text or copying it with a right-click.

How to Achieve This:

To accomplish this, we can leverage a JavaScript function that utilizes the browser's selection capabilities. Here's how it works:

Code Snippet:

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

Implementation:

In your HTML, include the following code to select text within the DIV element with ID "selectable":

<div>
Copy after login

When the user clicks anywhere within this DIV, the above JavaScript function will execute, highlighting all of its contents. This makes it incredibly easy to manipulate the text without the need for manual selection.

The above is the detailed content of How to Select All Text Within a DIV with One 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