0

<table id="z" border="1" width="20px" contenteditable>
  <tbody>
    <tr>
      <th></th>     
    </tr>    
  </tbody>
</table>

How to put the cursor to this cell (=table) using Javascript - as it works after a usual click? So after that, keyboard printing should work there. focus() doesn't work, but it works with <input>.

The expected result:

I use Google Chrome.

oleedd
  • 388
  • 2
  • 15
  • `document.getElementById("z").focus();` maybe? – obscure Oct 28 '20 at 10:51
  • @obscure Read more attentively. I have said that `focus()` doesn't work. – oleedd Oct 28 '20 at 10:52
  • I saw what you wrote. Even more, I've tested what I wrote before actually writing and apparently the cursor blinks after executing the above line. – obscure Oct 28 '20 at 10:54
  • @obscure We can test this via `console` and `setTimeout`. After this, I see focus blue highlighting, but no cursor and can't print. – oleedd Oct 28 '20 at 10:58
  • 1
    @oleedd maybe this is browser-specific. At least in FireFox it works flawlessly. – obscure Oct 28 '20 at 10:59
  • @obscure I use Chrome. Browser compatibility is bad. – oleedd Oct 28 '20 at 11:01
  • Does this answer your question? [Set focus on div contenteditable element](https://stackoverflow.com/questions/2388164/set-focus-on-div-contenteditable-element) – CBroe Oct 28 '20 at 11:01
  • @CBroe No, but thanks. There is `div` and here is `table`. So these questions are similar but not the same. – oleedd Oct 28 '20 at 11:08

2 Answers2

0

But it works!

let el = document.getElementById('z');
if (el !== null) {
    el.focus();
}
<table id="z" border="1" width="20px" contenteditable>
    <tbody>
      <tr>
        <th></th>
      </tr>    
    </tbody>
</table>
IRmmr
  • 1
0

As its a browser compatibility issue for focus() on an documentElement, Better you get the bug 467043 resolved from Chrome.

Rohit Gaikwad
  • 3,677
  • 3
  • 17
  • 40
  • It is said there that `focus()` doesn't work, but in my case, it works (because I see highlighting), but no cursor. – oleedd Oct 28 '20 at 18:54