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
Patricia ArquetteOriginal
2024-12-13 18:49:10531browse

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>

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);
    }
}

To use this code, simply add the following attribute to your DIV:

<div>

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!

Statement:
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