Home > Web Front-end > JS Tutorial > How Can I Get User-Selected Text from a Website Using JavaScript?

How Can I Get User-Selected Text from a Website Using JavaScript?

Linda Hamilton
Release: 2024-12-13 06:36:14
Original
483 people have browsed it

How Can I Get User-Selected Text from a Website Using JavaScript?

Get the Highlighted/Selected Text

Is it possible to obtain text highlighted or selected by a user within a website using jQuery?

Answer:

Getting the user-selected text is straightforward. Using jQuery offers no advantages because it can be accomplished using the window and document objects.

function getSelectionText() {
    let text = "";

    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }

    return text;
}
Copy after login

Alternatively, if you wish to consider selections in