zemaker
zemaker

Reputation: 181

Set focus on first-child <li> item that has <a> tag in it

Having a bit issue figuring out how to select only the first child in a li tag that has a link in it.

HTML:

<ul class="dropdown-menu" role="menu" aria-expanded="true">
  <li role="presentation" class="dropdown-header">Label</li>
  <li><a href="#">Select Me</a> </li>
</ul>

JavaScript:

dropdown.find('.dropdown-menu li:first-child a').focus();

In this particular case it doesn't get past the list item that is the "Label"

Upvotes: 2

Views: 3415

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48417

You can use eq method.

eq method reduce the set of matched elements to the one at the specified index.

$('body').find('.dropdown-menu li a').eq(0).css('color','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu" role="menu" aria-expanded="true">
  <li role="presentation" class="dropdown-header">Label 1</li>
  <li role="presentation" class="dropdown-header">Label 2</li>
  <li role="presentation" class="dropdown-header">Label 3</li>
  <li><a href="#">Select Me</a> </li>
</ul>

Another method is to use :first pseudo-selector.

first method reduce the set of matched elements to the first in the set.

$('body').find('.dropdown-menu li a:first').css('color','red');

$('body').find('.dropdown-menu li a:first').css('color','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu" role="menu" aria-expanded="true">
  <li role="presentation" class="dropdown-header">Label</li>
  <li><a href="#">Select Me</a> </li>
</ul>

Also, another solution that can help you is to use $.each method in order to search for the first li which has hyperlink element.

$('ul li').each(function(){
  if($(this).find('a').length>0){
    $(this).find('a').css('color','red');
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu" role="menu" aria-expanded="true">
  <li role="presentation" class="dropdown-header">Label 1</li>
  <li role="presentation" class="dropdown-header">Label 2</li>
  <li role="presentation" class="dropdown-header">Label 3</li>
  <li><a href="#">Select Me</a> </li>
</ul>

Upvotes: 2

user2233706
user2233706

Reputation: 7225

What about $('.dropdown-menu > li > a').first()?

Upvotes: 1

Related Questions