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?
The reason that's not working is simply because it's not stealing focus from the dev console. If you run the following code in your console and then quickly click in your browser window after, you will see it focus the search box: setTimeout(function() { $('input[name="q"]'). focus() }, 3000);
Use the setSelectionRange() method to move the cursor to the beginning of the input field. Call the focus() method on the input element. The focus method will move the cursor to the beginning of the element's value.
JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With