First (:first)
In this chapter you will learn:
- Description and Syntax for first selector
- Examples for first selector
- How to select the first span
- How to use first selector and id selector
- How to select the first row
Description and Syntax
$(':first')
select the first element within the matched set.
$('li:first')
selects the first<li>
element$('.myclass:first')
selects the first element with the classmyclass
Examples
The :first
pseudo-class is shorthand for
:eq(0)
. It could also be written as :lt(1)
.
The following code selects the first paragraph.
<html><!--from ja v a2 s .com-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var str = $("p:first").text()+"added";
$("p:last").html(str);
});
</script>
</head>
<body>
<body>
<p>java2s.com</p>
<p>java2s.com</p>
<p>java2s.com</p>
<p>java2s.com</p>
</body>
</html>
Select the first span element
The following code selects the first span
.
<html><!-- j a va 2s. c o m-->
<head>
<style>
.test{ border: 1px solid red; }
</style>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("span:first").text($(":hidden", document.body).length + " hidden elements.");
});
</script>
</head>
<body>
<span></span>
<div></div>
<div style="display:none;">java 2s.c om!</div>
<div></div>
<div></div>
<form>
<input type="hidden" />
<input type="hidden" />
<input type="hidden" />
</form>
<span></span>
</body>
</html>
Combine first with id selector
The following code combine the first selector and id selector.
<html><!-- jav a 2 s.c om-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#container").click(function (e) {
var $ch = $(e.target).children();
$("#results span:first").text($ch.length);
e.preventDefault();
return false;
});
});
</script>
</head>
<body>
<body>
<div id="container">
<div>
<p>This <span>is the <em>way</em> we</span>
write <em>the</em> demo,</p>
</div>
</div>
<span id="results">Found <span>0</span> children in <span>TAG</span>.</span>
</body>
</html>
Select first row
The following code selects the first row.
<html><!-- ja v a2 s. c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("tr:first").css("font-style", "italic");
});
</script>
</head>
<body>
<table>
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>
</body>
</html>
Next chapter...
What you will learn in the next chapter: