Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Not able to set focus to first li element within ul

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?

like image 298
Sushil Avatar asked May 13 '15 11:05

Sushil


People also ask

Can Li be focused?

You cannot normally focus li elements. But you can hover them, so you should use li:hover instead of li li:focus .

Does Li have to be inside UL?

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> ).

How do you get Li focusable?

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.

What elements are focusable?

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.


1 Answers

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

like image 89
Luca Colonnello Avatar answered Sep 19 '22 02:09

Luca Colonnello