Definition and Usage
first() Reduces the set of matching elements to the first element in the set.
Syntax
.first()
Detailed description
If given a jQuery object that represents a collection of DOM elements, .first() Method will construct a new jQuery object with the first matching element.
Consider the following page with a simple list:
<ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
We can apply this method to this collection of list items:
$('li').first().css('background-color', 'red');
Example display:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>:first选择器</title> <script type="text/javascript" src="jquery-2.0.3.js"></script> <style type="text/css"> body{ width:7%; height:100%; font-size:24px; font-weight:bold; background-color:#CCCCFF; text-align:center; } </style> <script type="text/javascript"> $(function(){ //设置ul中的第一个li的背景色,运用到:first选择器 $("li:first").css("background-color","#00DDDD"); //设置ol中的第一个li的背景色,运用到:first选择器 $(".two li:first").css("background-color","#0000CC"); //设置ol中的第一个li的字体颜色,运用到:first选择器 $(".two li:first").css("color","#FFFFFF"); }); </script> </head> <body> <div> <ul class="one"> <li>苹果</li> <li>梨子</li> <li>橘子</li> <li>西瓜</li> <li>荔枝</li> <li>葡萄</li> <li>香蕉</li> <li>香瓜</li> </ul> <ol class="two"> <li>苹果</li> <li>梨子</li> <li>橘子</li> <li>西瓜</li> <li>荔枝</li> <li>葡萄</li> <li>香蕉</li> <li>香瓜</li> </ol> </div> </body> </html>
The above is the detailed content of Basic introduction and example demonstration of first() selector in jQuery. For more information, please follow other related articles on the PHP Chinese website!