javascriptjqueryselection

How to select entire current line inside a div?


$('button').on('click', function(){
    let selection = window.getSelection();
    var ch;
    while(ch !== "\n"){
        selection?.modify('extend', 'backward', 'character');
        ch = selection.toString()[0];
    }
  var chh;
  selection = window.getSelection();
  while(chh !== "\n"){
        selection?.modify('extend', 'forward', 'character');
        let str = selection?.toString();
        chh = str.substr(str.length - 1);
    }
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre contenteditable>
This is the first line

This is the second line
This is the third line

This is the fourth line
</pre>
<button>CLICK</button>

Clicking on the button I need to select the current line - i.e. the line where the cursor is placed.

Please place your cursor inside the word second or third and click the button.

You'll see that only right side of line is selected instead of entire line.

Another problem is with first and fourth line because there is no "\n" character on the beginning / end of line.


Solution

  • If you use extend, you are changing the focus - not the anchor - of the selection range. This means the second modify still uses the original anchor.

    Use move to move the anchor.

    lineboundary checks for the end of a line, so you don't need to check for \n.

    $('pre').on('click', function() {
    let selection = window.getSelection();
    selection.modify('move', 'backward', 'lineboundary');
    selection.modify('extend', 'forward', 'lineboundary');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <pre contenteditable>
    This is the first line
    
    This is the second line
    This is the third line
    
    This is the fourth line
    </pre>