jQuery is a popular JavaScript library used to simplify many tasks in web development, including DOM manipulation. In web development, it is often necessary to add, delete, modify and check DOM elements, and deleting the last sub-element is also a common requirement. This article will introduce several methods to delete the last child element using jQuery.
Method 1: Use last()
method
jQuery provides the last()
method, which can select the last element of the current query result. By combining this method with the remove()
method, the last child element can be removed.
<!DOCTYPE html> <html> <head> <title>删除最后一个子元素示例</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div id="parent"> <div>子元素1</div> <div>子元素2</div> <div>子元素3</div> </div> <button id="deleteBtn">删除最后一个子元素</button> <script> $(document).ready(function(){ $('#deleteBtn').click(function(){ $('#parent').children().last().remove(); }); }); </script> </body> </html>
In the above code, by clicking the button to trigger the click event of deleteBtn
, jQuery will select the last of all child elements of the parent
element and delete it .
Method 2: Use :last-child
selector
In addition to using the last()
method, you can also use the selector provided by jQuery:last-child
Select the last child element and then call the remove()
method to delete it.
<!DOCTYPE html> <html> <head> <title>删除最后一个子元素示例</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div id="parent"> <div>子元素1</div> <div>子元素2</div> <div>子元素3</div> </div> <button id="deleteBtn">删除最后一个子元素</button> <script> $(document).ready(function(){ $('#deleteBtn').click(function(){ $('#parent :last-child').remove(); }); }); </script> </body> </html>
In the above code, the event is also triggered by clicking the button, selecting the last child element of the parent
element and deleting it.
Summary:
The above are two methods of using jQuery to delete the last child element. Developers can choose the appropriate method to operate DOM elements according to the actual situation. The flexibility and convenience of jQuery make operating DOM simple and easy to understand, improving the efficiency of Web development.
The above is the detailed content of How to remove last child element in jQuery?. For more information, please follow other related articles on the PHP Chinese website!