Home > Web Front-end > CSS Tutorial > How Can I Automatically Select All Text Within a DIV on Click?

How Can I Automatically Select All Text Within a DIV on Click?

Patricia Arquette
Release: 2024-12-13 18:49:10
Original
539 people have browsed it

How Can I Automatically Select All Text Within a DIV on Click?

Highlight and Select DIV Text on Mouse Click

To simplify text selection tasks, it's possible to highlight and select the entire contents of a DIV when the user clicks on it. This eliminates the need for manual highlighting, ensuring that none of the text is missed.

Consider the following example:

<div>
Copy after login
Copy after login

When a user clicks anywhere within this DIV, the entire URL should be highlighted, allowing them to easily drag or copy the selected text.

To achieve this, you can utilize the following 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 use this code, simply add the following attribute to your DIV:

<div>
Copy after login
Copy after login

Now, when the user clicks on the DIV, the entire text will be automatically selected, making it convenient to perform various text-related actions.

The above is the detailed content of How Can I Automatically Select All Text Within a DIV on 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