1

This is more of a JS and HTML question than svelte.

I want to select all the text in the field when the element gets focus. It works fine when the element is an input element but it does not work with td. How can I achieve this with td (no jQuery)?

<script>
    function handleFocus(e) {
        e.target.select();
    }
</script>

<input on:focus={handleFocus} value="Testing"/>
<td on:focus={handleFocus} contenteditable="true">Testing</td>

Svelte REPL

isherwood
  • 58,414
  • 16
  • 114
  • 157
Ben Quan
  • 773
  • 11
  • 25

1 Answers1

2

You need to create a selection range.

<script>
function handleFocus(e) {
        e.target.select();
    }
    
    function tdFocus(e) {
        const el = e.target
        const range = document.createRange();
       range.selectNodeContents(el);
        const sel = window.getSelection();
       sel.removeAllRanges();
       sel.addRange(range);
    }
</script>

<input on:focus={handleFocus} value="Testing"/>
<td on:focus={tdFocus} contenteditable="true">Testing</td>

Svelte REPL

Mina
  • 14,386
  • 3
  • 13
  • 26