加载中...

:first-child


概述    first-child selector

返回值:Array<Element(s)>

描述:选择所有父级元素下的第一个子元素。

  • V : 1.1.4jQuery( ":first-child" )

虽然:first只匹配一个单独的元素,但是:first-child选择器可以匹配多个:即为每个父级元素匹配第一个子元素。这相当于:nth-child(1)

示例

实例

在每个 ul 中查找第一个 li

HTML 代码:
  1. <ul>
  2. <li>John</li>
  3. <li>Karl</li>
  4. <li>Brandon</li>
  5. </ul>
  6. <ul>
  7. <li>Glen</li>
  8. <li>Tane</li>
  9. <li>Ralph</li>
  10. </ul>
jQuery 代码:
  1. $("ul li:first-child")
结果:
  1. [ <li>John</li>, <li>Glen</li> ]

实例

给每个匹配的 div 中查找第一个 span,并加上下划线及增加鼠标悬停效果。

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>first-child demo</title>
  6. <style>
  7. span {
  8. color: #008;
  9. }
  10. span.sogreen {
  11. color: green;
  12. font-weight: bolder;
  13. }
  14. </style>
  15. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  16. </head>
  17. <body>
  18. <div>
  19. <span>John,</span>
  20. <span>Karl,</span>
  21. <span>Brandon</span>
  22. </div>
  23. <div>
  24. <span>Glen,</span>
  25. <span>Tane,</span>
  26. <span>Ralph</span>
  27. </div>
  28. <script>
  29. $( "div span:first-child" )
  30. .css( "text-decoration", "underline" )
  31. .hover(function() {
  32. $( this ).addClass( "sogreen" );
  33. }, function() {
  34. $( this ).removeClass( "sogreen" );
  35. });
  36. </script>
  37. </body>
  38. </html>

运行一下


还没有评论.