Home >Web Front-end >Front-end Q&A >How to query the last child element with jquery
Two methods: 1. Use children() and ":last-child" selector, syntax "$(parent element).children(":last-child")". 2. Use children() and eq(), the syntax is "$(parent element).children().eq(-1)".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
Two methods for jquery to query the last child element
Method 1: Use children()
and:last-child
selector
Use children() to get all direct child elements under the specified parent node
Use:last-child to select the last element in the child element collection, that is, the last child element
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function () { $("button").click(function () { $("ul").children(":last-child").css("color","red"); }) }) </script> </head> <body> <ul> <li>香蕉</li> <li>苹果</li> <li>梨子</li> <li>橘子</li> </ul> <button>父元素ul的最后一个子元素</button> </body> </html>
Method 2: Use children() and eq()
Use children() to get all direct child elements under the specified parent node
Use eq(-1) to select the last element in the sub-element set, that is, the last sub-element
Based on the above example, modify:
$(function() { $("button").click(function() { $("ul").children().eq(-1).css("color", "red"); }) })
[Recommended learning: jQuery video tutorial, web front-end video]
The above is the detailed content of How to query the last child element with jquery. For more information, please follow other related articles on the PHP Chinese website!