SoFunction
Updated on 2025-04-06

jQuery: first selector usage example

This article describes the usage of the first selector in jQuery. Share it for your reference. The specific analysis is as follows:

This selector matches the first element in the specified element collection.

Syntax structure:

Copy the codeThe code is as follows:
$(":first")

In use, it should generally be used in conjunction with other selectors, such as class selectors and element selectors, etc. For example:

Copy the codeThe code is as follows:
$("li:first").css("color","green")

The above code can set the font color in the first li element in the li element collection to green.
If not used with other selectors, the default state is to use with * selectors, for example $(":first") is equivalent to $("*:first").

Example code:

Example 1:

Copy the codeThe code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https:///" />
<title>I</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8."></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("li:first").css("color","green")
  })
})
</script>
</head>
<body>
<div>
  <ul>
<li class="zhuanqu">html zone</li>
<li class="zhuanqu">div+css zone</li>
<li class="zhuanqu">jQuery Zone</li>
<li class="zhuanqu">Javascript area</li>
  </ul>
</div>
<button>Click to view the effect</button>
</body>
</html>

The above code can set the font color in the first li element in the li element collection to green.

Example 2:

Copy the codeThe code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https:///" />
<title>I</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8."></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $(":first").css("color","green")
  })
})
</script>
</head>
<body>
<div>
  <ul>
<li class="zhuanqu">html zone</li>
<li class="zhuanqu">div+css zone</li>
<li class="zhuanqu">jQuery Zone</li>
<li class="zhuanqu">Javascript area</li>
  </ul>
  <div>
<span>I</span>
<span>The sun is coming</span>
  </div>
</div>
<button>Click to view the effect</button>
</body>
</html>

Since the above code does not specify a selector that matches the :first selector, it will be used with the * selector by default. Therefore, the above code will set the font color in all elements to green.

I hope this article will be helpful to everyone's jQuery programming.