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?

8
  • Just curious, could you use an ID instead of class name? Commented Mar 27, 2015 at 12:25
  • document.querySelector(".input-search").focus(); works! and $(".input-search").focus(); provided you have jQuery included. Commented Mar 27, 2015 at 12:26
  • @LShetty it does not for me. Commented Mar 27, 2015 at 12:27
  • @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"> Commented Mar 27, 2015 at 12:27
  • You may have other errors which is why. This works - http://jsfiddle.net/lshettyl/y0f04L88/ Commented Mar 27, 2015 at 12:29

1 Answer 1

37

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.

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

4 Comments

Oh Man! You made the day for me. Thanks for this awesome answer and I am sure that it would help many people.
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?
@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.
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.