4

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?

2

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.