如何用jQuery为最后一个段落元素添加一个类
在这篇文章中,我们将学习如何使用jQuery为最后一个段落元素添加一个类。为了给最后一个段落元素添加一个类,我们使用last()和addClass()方法。jQuery的last()函数是一个内置的函数,用来寻找指定元素的最后一个元素。
语法:
$(selector).last()
addClass()方法是用来给每个选定的元素添加更多的类和它们各自的属性。它也可以用来改变所选元素的属性。在这里,类的名称可以直接与将要被选中的元素一起使用。
语法:
$(selector).addClass(className);
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.GFG {
color: green;
font-size: 24px;
font-weight: bold;
}
</style>
<!-- Import jQuery cdn library -->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function () {
("button").click(function () {
$("p").last().addClass("GFG");
});
});
</script>
</head>
<body style="text-align: center;">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
How to add a class to the last
paragraph element using jQuery?
</h3>
<p>GeeksforGeeks computer science portal</p>
<button>Click Here!</button>
</body>
</html>
输出:
在点击按钮之前:
点击按钮后: