Selecting text in an element (akin to highlighting with your mouse)

后端 未结 16 1673
孤街浪徒
孤街浪徒 2020-11-21 05:58

I would like to have users click a link, then it selects the HTML text in another element (not an input).

By \"select\" I mean the same way you would select

16条回答
  •  一整个雨季
    2020-11-21 06:27

    For any tag one can select all text inside that tag by this short and simple code. It will highlight the entire tag area with yellow colour and select text inside it on single click.

    document.onclick = function(event) {
        var range, selection;
    event.target.style.backgroundColor = 'yellow';
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(event.target);
            selection.removeAllRanges();
            selection.addRange(range);
    };
    

提交回复
热议问题