如何用jQuery选择一个具有特定类别的div
给出一个包含许多带类的div元素的HTML文档。这里的任务是选择一个具有某个类的div,并且没有其他类。有两种方法来解决这个问题。其中一种是使用方法,另一种是使用非选择器。
方法1:首先,使用jQuery选择器选择具有特定类别的DIV,然后使用:not选择器
来忽略特定类别的元素。
- 例子。这个例子实现了上述方法。
<!DOCTYPE HTML>
<html>
<head>
<title>
Select a div with a certain class,
that doesn't have another class.
</title>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
.div {
background: green;
height: 50px;
width: 200px;
margin: 0 auto;
color: white;
border: 2px solid black;
}
</style>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body>
<h1>
GeeksforGeeks
</h1>
<p>
Click on button to select a div with a certain
class, that doesn't have another class.
</p>
<!-- div elements -->
<div class="first div">
This is first Div
</div>
<br>
<div class="second div">
This is second Div
</div>
<br>
<div class="third div">
This is third Div
</div>
<br>
<button onClick="GFG_Fun()">
click here
<br>
<p id="geeks">
</p>
<script>
/* main function */
function GFG_Fun() {
/* using the :not selector */
('.div:not(.first)')
.css("background-color", "#173F5F");
('#geeks')
.text("DIV Box of class 'first' is not selected.");
}
</script>
</body>
</html>
- 输出:
方法2:首先,使用jQuery选择器选择具有特定类别的DIV,然后使用.not()方法忽略特定类别的元素。
- 例子。这个例子实现了上述方法。
<!DOCTYPE HTML>
<html>
<head>
<title>
Select a div with a certain class,
that doesn't have another class.
</title>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
.div {
background: green;
height: 50px;
width: 200px;
margin: 0 auto;
color: white;
border: 2px solid black;
}
</style>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body>
<h1>
GeeksforGeeks
</h1>
<p>
Click on button to select a div with a certain
class, that doesn't have another class.
</p>
<!-- div elements -->
<div class="first div">
This is first Div
</div>
<br>
<div class="second div">
This is second Div
</div>
<br>
<div class="third div">
This is third Div
</div>
<br>
<button onClick="GFG_Fun()">
click here
<br>
<p id="geeks">
</p>
<script>
/* main function */
function GFG_Fun() {
/* using the .not() method */
('.div').not('.first')
.css("background-color", "#173F5F");
('#GFG_DOWN')
.text("DIV Box of class 'first' is not selected.");
}
</script>
</body>
</html>
- 输出: