jquery set focus on dynamic content?

In jquery I've appended a <li> element to an unordered list.

How do I focus on the newly created <li> ?

If I do the following:

$("ul").append('<li><input type="text" value="Hi!"></li>');
$("li:last").focus(); //doesn't work because new <li> isn't in dom yet

the focus doesn't work, as noted above.

I know jquery 1.4.2 has a live() event handler which allows you load event handlers to dynamically added elements, but I'm not sure what I'm doing wrong:

$(document).ready(function () {

    $('li').live('load', function () {



You can only set the focus to elements which can hold the focus. By default a list item cannot. This is why your first example fails, not because it isn't in the DOM (it is in the DOM, that is what append does)

In general you should use elements designed to hold the focus (i.e. set the focus on the input not the list item). You can also (but this is less backwards compatible and less logical) use HTML5's tabindex (probably setting it to 0).

onload will not work because list items do not load external content.


You can try this, $(YourElement).trigger("focus").


This is an old post I know, but a simple way to solve this issue is to create a text input in your HTML and set its CSS to "display: none;". On the LI's click event, set the focus in this input and listen to its keypress events.

I've done it and it works like a charm.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.