如何用jQuery找到被点击元素的类别
在这篇文章中,我们将使用jQuery找到被点击元素的类别。为了找到被点击元素的类别,我们使用this.className属性。className属性用于设置或返回一个元素的类属性的值。使用这个属性,用户可以将一个元素的类别改为所需的类别。
步骤:
在这里,我们使用this.className属性来获取当前div元素的类别名称。在这里,我们添加了五个具有不同类名的div元素,然后使用jQuery this.className属性来获取被点击的div元素的类名并显示在控制台。
语法:
$("div").click(function () {
var getClass = this.className;
console.log(getClass);
});
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to find the class of the
clicked element using jquery?
</title>
<!-- Import jQuery cdn library -->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function () {
("div").click(function () {
var getClass = this.className;
console.log(getClass);
});
});
</script>
</head>
<body style="text-align: center;">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
How to find the class of the
clicked element using jquery?
</h3>
<div class="main">Main Div</div>
<div class="GFG">GFG</div>
<div class="Geeks">Geeks</div>
<div class="G4G">GeeksforGeeks</div>
<div class="welcome">Welcome</div>
</body>
</html>
输出: