I have below code:
<ul id='someId'>
<li class='someClass'>
</li>
</ul>
I want to set focus on first li element within ul based on some condition.
My first attempt is like this:
var ul = document.getElementById('someId');
var child = ul.childNodes[0];
child.focus();
My second attempt is like this :
var y = document.getElementsByClassName('someClass');
var aNode = y[0];
aNode.focus();
But none of the above works
Any ideas?
You cannot normally focus li elements. But you can hover them, so you should use li:hover instead of li li:focus .
The <li> HTML element is used to represent an item in a list. It must be contained in a parent element: an ordered list ( <ol> ), an unordered list ( <ul> ), or a menu ( <menu> ).
add tabindex='0' property if you want your non input element to be reachable via non sequential keyboard navigation. add tabindex='-1' property if you want your non input element to be focusable, but not reachable via sequential keyboard navigation.
Elements of the following type are focusable if they are not disabled: input , select , textarea , button , and object . Anchors are focusable if they have an href or tabindex attribute. area elements are focusable if they are inside a named map, have an href attribute, and there is a visible image using the map.
The problem is that you can't focus a non input element without setting tabIndex.
<li tabIndex="-1">...</li>
You can Try this fiddle: jsfiddle
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