Is it possible to use the :first and :last selectors with jQuery’s on selector?
I want the first link in each list item to trigger the alert. However, at the moment, only the very first link triggers it.
The JavaScript code:
<script type="text/javascript">
$(document).ready( function(){
$('ul').on("click", "li a:first", function(event) {
alert("test");
});
}
</script>
And the HTML:
<ul>
<li>
<a href="#">Trigger</a>
<a href="#">Don't Trigger</a>
</li>
<li>
<a href="#">Trigger</a>
<a href="#">Don't Trigger</a>
</li>
</ul>
Use
:first-childinsteadDemo: http://jsfiddle.net/joycse06/tuJnv/1/
As the doc says
:firstwill match only one element, first on selected set of elements. Where:first-childwill find one(the first child) for each parent which is what you want.Doc on
:firstand:first-child