Skip to content Skip to sidebar Skip to footer

Jquery Selectors For First Li

I need an onclick event, when the user clicks on the first li aka(Any Date).How do I select that element using jQuery?

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 herereturnfalse; // 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");
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulid="ui-id-1"class="ui-menu ui-widget ui-widget-content"role="menu"tabindex="0"aria-activedescendant="ui-id-5"><liclass="ui-menu-item"id="ui-id-2"tabindex="-1"role="menuitem"><ahref="#">Any Date</a></li><liclass="ui-menu-item"id="ui-id-3"tabindex="-1"role="menuitem"><ahref="#">Past 7 days</a></li><liclass="ui-menu-item"id="ui-id-4"tabindex="-1"role="menuitem"><ahref="#">Past month</a></li><liclass="ui-menu-item"id="ui-id-5"tabindex="-1"role="menuitem"><ahref="#">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"