jQuery – First child & last child selector example

The :first-child is used to select all elements that are the first child of their parent, which is a shorthand for :nth-child(1).

Examples

  1. $(‘li:first-child’) – selects all elements matched by <li> that are the first child of their parent.
  2. $(tr:first-child’) – selects all elements matched by <tr> that are the first child of their parent.

The :last-child is used to select all elements that are the last child of their parent.

Examples

  1. $(‘li:last-child’) – selects all elements matched by <li> that are the last child of their parent.
  2. $(tr:last-child’) – selects all elements matched by <tr> that are the last child of their parent.

jQuery Example

A simple example to demonstrate the use of the first child and last child function to add “li” background color dynamically.


<html>
<head>
<title>jQuery first child and last child example</title>
 
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>

<body>

<h1>jQuery first child and last child example</h1>

<ul>
	<li>li #1</li>
	<li>li #2</li>
	<li>li #3</li>
	<li>li #4</li>
	<li>li #5</li>
</ul>

<button>li:first-child</button>
<button>li:last-child</button>

<script type="text/javascript">
    $("button").click(function () {
      var str = $(this).text();
      $("li").css("background", "white");
      $(str).css("background", "coral");
    });
</script>

</body>
</html>

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
jQuery Tutorials | J2EE Web Development Tutorials Recent comment authors
newest oldest most voted
trackback
jQuery Tutorials | J2EE Web Development Tutorials

[…] First child & Last child selectors Select the first child or last child element with jQuery, shorthand for ntg-child. […]