Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for document.execCommand('selectAll',false,null) [duplicate]

I have the following code which allows me to select a div text each time the user click on it:

<table>
  <tr>
    <td>
      <div contenteditable onClick="document.execCommand('selectAll',false,null)">I'm editable</div>
    </td>
  </tr>
  <tr>
    <td>
      <div contenteditable>I'm also editable</div>
    </td>
  </tr>
  <tr>
    <td>I'm not editable</td>
  </tr>
</table>

My problem is that document.execCommand is deprecated and I want to change it for a good alternative. How can I do that?

like image 488
Ricardo Rocha Avatar asked Sep 07 '25 04:09

Ricardo Rocha


1 Answers

Based in Alvaro Tihanyi comment and Shilly comment I found out this solution:

function selectText(element) {
    if (document.selection) { // IE
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(element);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}
<table>
  <tr>
    <td>
      <div id="selectable" contenteditable onclick="selectText(this)">I'm editable</div>
    </td>
  </tr>
  <tr>
    <td>
      <div contenteditable>I'm also editable</div>
    </td>
  </tr>
  <tr>
    <td>I'm not editable</td>
  </tr>
</table>
like image 95
Ricardo Rocha Avatar answered Sep 10 '25 15:09

Ricardo Rocha