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
- $(‘li:first-child’) – selects all elements matched by <li> that are the first child of their parent.
- $(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
- $(‘li:last-child’) – selects all elements matched by <li> that are the last child of their parent.
- $(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
Comments
Subscribe
0 Comments