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 () {
alert("hi!");
$("li:last").focus();
});
});
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")
.
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