Max Koretskyi
Max Koretskyi

Reputation: 105507

Why user selection is rendered on the screen?

I'm trying to pragmatically create the user selection. Here is the plunker. Here is the simple setup:

<p>Tim O'Reilly calls for a Blogger Code of Conduct. His proposals are:</p>
<ol>
    <li>Take responsibility not just for your own words, but for the
        comments you allow on your blog.</li>
    <li>Label your tolerance level for abusive comments.</li>
    <li>Consider eliminating anonymous comments.</li>
</ol>

<script>
    var range = document.createRange();
    var startPar = document.querySelector('p').firstChild;
    var endLi = document.querySelector('li:nth-child(2)').firstChild;
    range.setStart(startPar,13);
    range.setEnd(endLi,17);
    console.log(range.toString());
</script>

Everything seems to be working fine, I get the expected output to console, however the text is not selected on the screen. Is it by design?

Upvotes: 0

Views: 36

Answers (1)

Antony Harfield
Antony Harfield

Reputation: 920

You have found the range, but now you need to tell the browser to select it. Example:

var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

Upvotes: 1

Related Questions