Home > Web Front-end > JS Tutorial > body text

Basic introduction and example demonstration of first() selector in jQuery

巴扎黑
Release: 2017-06-22 15:23:31
Original
1409 people have browsed it

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>
Copy after login

We can apply this method to this collection of list items:

$(&#39;li&#39;).first().css(&#39;background-color&#39;, &#39;red&#39;);
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template