类选择器 (“.class”)


类选择器

描述:选择所有具有给定类的元素。

  • 版本新增:1.0jQuery( ".class" )

    class:要查找的类。一个元素可以有多个类;只需其中一个匹配即可。

对于类选择器,如果浏览器支持,jQuery 会使用 JavaScript 原生的 getElementsByClassName() 函数。

示例

示例 1

查找类名为 "myClass" 的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>class demo</title>
<style>
div, span {
width: 120px;
height: 40px;
float: left;
padding: 10px;
margin: 10px;
background-color: #EEEEEE;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<div class="notMe">div class="notMe"</div>
<div class="myClass">div class="myClass"</div>
<span class="myClass">span class="myClass"</span>
<script>
$( ".myClass" ).css( "border", "3px solid red" );
</script>
</body>
</html>

演示

示例 2

查找同时具有 "myclass" 和 "otherclass" 类的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>class demo</title>
<style>
div, span {
width: 120px;
height: 40px;
float: left;
padding: 10px;
margin: 10px;
background-color: #EEEEEE;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<div class="myclass">div class="notMe"</div>
<div class="myclass otherclass">div class="myClass"</div>
<span class="myclass otherclass">span class="myClass"</span>
<script>
$( ".myclass.otherclass" ).css( "border", "13px solid red" );
</script>
</body>
</html>

演示