Home >Web Front-end >JS Tutorial >Detailed explanation of jQuery child element selector
This article mainly introduces the child element selector of jQuery selector to you in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <link rel="stylesheet" href="imooc.css" rel="external nofollow" type="text/css"> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <h2>子元素筛选选择器</h2> <h3>:first-child、:last-child、:only-child</h3> <p class="left first-p"> <p class="p"> <a>:first-child</a> <a>第二个元素</a> <a>:last-child</a> </p> <p class="p"> <a>:first-child</a> </p> <p class="p"> <a>:first-child</a> <a>第二个元素</a> <a>:last-child</a> </p> </p> <script type="text/javascript"> //查找class="first-p"下的第一个a元素 //针对所有父级下的第一个 $(".first-p a:first-child").css("color", "#CD00CD"); </script> <script type="text/javascript"> //查找class="first-p"下的最后一个a元素 //针对所有父级下的最后一个 //如果只有一个元素的话,last也是第一个元素 $(".first-p a:last-child").css("color", "red"); </script> <script type="text/javascript"> //查找class="first-p"下的只有一个子元素的a元素 $(".first-p a:only-child").css("color", "blue"); </script> <h3>:nth-child、:nth-last-child</h3> <p class="left last-p"> <p class="p"> <a>:first-child</a> <a>第二个元素</a> <a>第三个元素</a> <a>:last-child</a> </p> <p class="p"> <a>:first-child</a> <a>第二个元素</a> </p> <p class="p"> <a>:first-child</a> <a>第二个元素</a> <a>第三个元素</a> <a>:last-child</a> </p> </p> <script type="text/javascript"> //查找class="last-p"下的第二个a元素 $(".last-p a:nth-child(2)").css("color", "#CD00CD"); </script> <script type="text/javascript"> //查找class="last-p"下的倒数第二个a元素 $(".last-p a:nth-last-child(2)").css("color", "red"); </script> </body> </html>
Related recommendations:
Detailed introduction to the usage of CSS sub-element selector
The above is the detailed content of Detailed explanation of jQuery child element selector. For more information, please follow other related articles on the PHP Chinese website!