亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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?

Dec 13, 2024 am 06:36 AM

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

Alternatively, if you wish to consider selections in