3

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
  • Care to explain the use case? We have https://developer.mozilla.org/en-US/docs/Web/API/Selection and https://developer.mozilla.org/en-US/docs/Web/API/Range these days. But afaik, we cannot just copy that to like the clipboard and such ( which also used execCommand ) so a `new Range()` might not fix the issue. If you just want to highlight the text so users can immediately type, I use an input with all stylings removed instead of a div, to get that functionality out of the box with `.select()`. – Shilly Jan 23 '20 at 14:56
  • Does this answer your question? [Select all DIV text with single mouse click](https://stackoverflow.com/questions/1173194/select-all-div-text-with-single-mouse-click) – Álvaro Tihanyi Jan 23 '20 at 14:56

1 Answers1

3

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>
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
  • Use an actual event listener so you can use `event.target` to refer to the div instead of an inline event in the HTML that passes a string to use as a selector. – Shilly Jan 23 '20 at 15:04