Sushil
Sushil

Reputation: 472

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?

Upvotes: 17

Views: 24842

Answers (2)

Luca Colonnello
Luca Colonnello

Reputation: 1456

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

Upvotes: 45

TheWizardOfTN
TheWizardOfTN

Reputation: 186

An 'li' can't have focus, however an 'input' can, so you write yourself the following script:

function installLI(obj){
       var ul = document.createElement('ul');
       obj.appendChild(ul);
       var li = document.createElement('li');
       var txt = document.createElement('input');
       li.appendChild(txt);
       ul.appendChild(li);
       txt.focus();
       li.removeChild(txt);
}

Where 'obj' is the object (like an editable div) that you're appending your list to.

Upvotes: 0

Related Questions