類別選擇器 (“.class”)


類別選擇器

說明:選取所有具有指定類別的元素。

  • 新增版本:1.0jQuery( ".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.jquery.com/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.jquery.com/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>

示範