8
votes

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?

1
Just curious, could you use an ID instead of class name?Mark
document.querySelector(".input-search").focus(); works! and $(".input-search").focus(); provided you have jQuery included.lshettyl
@LShetty it does not for me.rahulserver
@Mark the element does not have an id. Its Html is: <input type="text" class="input input-search" tabindex="2" value="" data-reactid=".0.1:$main.2.2.2.1">rahulserver
You may have other errors which is why. This works - http://jsfiddle.net/lshettyl/y0f04L88/lshettyl

1 Answers

32
votes

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.