Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus an element created on the fly

Tags:

javascript

dom

how to focus an element created on the fly?

like image 249
Bijumon Attipil Avatar asked Dec 29 '22 05:12

Bijumon Attipil


2 Answers

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

You can test it out here.

like image 53
Nick Craver Avatar answered Dec 31 '22 15:12

Nick Craver


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.

like image 33
Andrzej Doyle Avatar answered Dec 31 '22 14:12

Andrzej Doyle