JQuery Selectors For First Li
$('ul li').first().click(function()
{
// do something
});
Example : https://jsfiddle.net/3mb8ep19/1/
Solution 2:
Well it has an id
so you can use that in your selector. You are targeting the link inside the li
correct?
$("#ui-id-2 a").click(function(){
// function goes here
return false; // the link itself has a behaviour associated with it so we want to stop that
});
Otherwise for something more generic you can use the :first-child selector.
Note : While :first matches only a single element, the :first-child selector can match more than one: one for each parent.
$("ul.ui-menu li:first-child a").click(function(){});
Solution 3:
You can use :first-child
$("ul.ui-menu li.ui-menu-item:first-child").on("click", function() {
$(this).css("background", "red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ui-id-1" class="ui-menu ui-widget ui-widget-content" role="menu" tabindex="0" aria-activedescendant="ui-id-5">
<li class="ui-menu-item" id="ui-id-2" tabindex="-1" role="menuitem">
<a href="#">Any Date</a>
</li>
<li class="ui-menu-item" id="ui-id-3" tabindex="-1" role="menuitem">
<a href="#">Past 7 days</a>
</li>
<li class="ui-menu-item" id="ui-id-4" tabindex="-1" role="menuitem">
<a href="#">Past month</a>
</li>
<li class="ui-menu-item" id="ui-id-5" tabindex="-1" role="menuitem">
<a href="#">Past year</a>
</li>
</ul>
Solution 4:
You can use any of the methods given below to select first li element.
1. using jQuery :nth-child selector It selects the child of the element using its position. The value 1 select the li item located at first position.
$( "ul li:nth-child(1)" ).click(function(){
//do something here
});
2. using jQuery :first selector It selects the first li item.
$( "ul li:first" ).click(function(){
//do something here
});
3. using jQuery :eq() selector The li element starts with index 0. To select first item, you have use 0 as its value.
$( "ul li:eq(0)" ).click(function(){
//do something here
});
See this: Get the First Element of li Using jquery for live examples.
Post a Comment for "JQuery Selectors For First Li"