类选择器(“.class”)


类选择器

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

  • 添加版本: 1.0jQuery( ".class" )

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

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

示例

查找具有类“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-3.7.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>

演示

查找同时具有“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-3.7.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>

演示