.focus() Not Focusing On New Element

.focus() Not Focusing On New Element

I have a function for renaming certain divs. The way I’m trying to get it to work is like this:

  • User right clicks div
  • User clicks ‘Rename’ on context menu
  • Div gets an input element and is automatically focused
  • The input gets submitted after pressing enter or clicking the screen

I have most of the steps done but the input element is not being focused after I click ‘rename’. Here’s the code:

function Rename( ){
    ClickedFile.innerHTML = "<input class='Rename' type='text' value='" + ClickedFile.innerHTML + "'>";

The ClickedFile is the node that was right clicked. Changing The innerHTML works fine but the .focus() does not and I’m not sure why. I don’t get any errors on the console, either.

I’ve also tried using:


None of them have worked.


  • I know using JQuery might help, but I’m more interested in finding out why this isn’t working.

  • I fixed the problem. It has something to do with event handlers. My answer is posted below.

You have to add the element as part of DOM

var input = document.createElement("input");
input.className = "Rename";
input.type = "text";

input.focus(); // should work now

see the fiddle