how to focus an element created on the fly?
Asked
Active
Viewed 5,690 times
5 Answers
8
Just call .focus()
on the element after it's added to the DOM, for example:
var input = document.createElement("input"); //create it
document.body.appendChild(input); //append it
input.focus(); //focus it

Nick Craver
- 623,446
- 136
- 1,297
- 1,155
-
1... which works so long as the element created is one capable of receiving the focus. – Tim Down Nov 15 '10 at 11:18
4
The focus method will do this. If you have a reference to the newly-created element called elem
, then simply invoke:
elem.focus();
Note that you'll need to do this after inserting the element into the document at the appropriate point, of course.

Andrzej Doyle
- 102,507
- 33
- 189
- 228
0
Try this code,
var txtObj = document.createElement("input");
window.document.body.appendChild(a);
txtObj.focus();

Chinmayee G
- 7,947
- 2
- 31
- 41
0
<script>
$('#container').append('<input type="text">');
$('#container').find('input:last').focus();
</script>

Murat Tutumlu
- 762
- 6
- 16
-
-
You can add id or class to the input. Or can do :last. I will update the answer with :last – Murat Tutumlu Oct 09 '17 at 02:18
-2
You can use setTImeOut
setTimeout(function() {
$("#id_of_element_created").focus().select();
}, 100);

notnotundefined
- 3,493
- 3
- 30
- 39