Main Tutorials

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 Author

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

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments