10

This is in reference to this SO answer. I am trying the same on web.whatsapp.com (chrome) for its input search field. Here is my code to do it:

document.getElementsByClassName("input input-search")[0].focus()
document.getElementsByClassName("input input-search")[0].select()

Above does not work from chrome console.

Also the jQuery code:

$(".input-search").focus() 

does not work. What could be the reason that I don't see the cursor even after executing above methods?

Community
  • 1
  • 1
rahulserver
  • 10,411
  • 24
  • 90
  • 164

1 Answers1

36

I think this is not related to issue with class, id, javascript or jQuery. It's the way browser console works. The console gets focus after each command is run. So the focus will not work for other inputs from the console.

To test it, run this code in console.

setTimeout(function(){$(".input.input-search").focus()},5000);

After executing it immediately click anywhere on the page to take focus out of console. Now after 5 seconds, the focus will set on input.

K K
  • 17,794
  • 4
  • 30
  • 39
  • 5
    Oh Man! You made the day for me. Thanks for this awesome answer and I am sure that it would help many people. – rahulserver Mar 27 '15 at 12:47
  • In many cases, I see that `setTimeout(function(){$(".input.input-search").focus()},0);` does the trick, while `$(".input.input-search").focus();` doesn't, even though both are essentially the same. Why might this be? – SexyBeast Apr 21 '16 at 14:16
  • 2
    @AttitudeMonger Both aren't same. setTimeout function adds a task to the queue which is executed after a given interval, while .focus() is not added to any queue for execution. So, in case of setTimeout, a gap of milliseconds might be enough to perform the above said task. You may read more about how setTimeout works. – K K Apr 22 '16 at 04:25
  • 1
    related: when console was open I didn't see the cursor in the browser after elment.focus() although typing proved it was in the right place. Closing the console did indeed show the cursor where expected. Thanks for the lead! – cuka Feb 25 '23 at 03:04