user3013365 user3013365 - 3 months ago 49
HTML Question

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?

Answer

The problem is that you can't focus a non input element without setting tabIndex.

<li tabindex="-1">...</li>

Try this fiddle: jsfiddle

Comments