如何在jQuery中不使用addClass()方法为一个元素添加类
任务是在jQuery的帮助下,不使用addClass()方法为元素添加一个新的类。有两种方法在下面讨论。
方法1:为了执行操作,我们可以使用toggleClass()方法来切换我们想要添加到元素的类。
- 示例:
<!DOCTYPE HTML>
<html>
<head>
<title>
How to add class to an element without
addClass() method in jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<style>
#el {
background: green;
}
.newClass {
color: white;
}
</style>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"></p>
<p id="el">This is the element</p>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="GFG_DOWN"></p>
<script>
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Click on the button to "
+ "perform the operation.";
function GFG_Fun() {
$('#el').toggleClass('newClass');
el_down.innerHTML = "Class has been added";
}
</script>
</body>
</html>
- 输出:
方法2:我们也可以使用attr()方法和prop()方法为元素添加一个新的属性’class’。
- 示例:
<!DOCTYPE HTML>
<html>
<head>
<title>
How to add class to an element without
addClass() method in jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<style>
#el {
background: green;
}
.newClass {
color: white;
}
</style>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"></p>
<p id="el">This is the element</p>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="GFG_DOWN"></p>
<script>
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Click on the button to "
+ "perform the operation.";
function GFG_Fun() {
$('#el').attr('class', 'newClass');
el_down.innerHTML = "Class has been added";
}
</script>
</body>
</html>
- 输出: