:nth-last-of-type()

最後の要素から数えて、その親要素のn番目の子要素を全て選択します。

$(":nth-last-of-type(index/even/odd/equation)") 1.9追加

引数 説明
index マッチした各子要素のインデックス、 最後(1)から開始して、 even(偶数)またはodd(奇数)の文字列、 または方程式を指定します。 (例::nth-last-of-type(even):nth-last-of-type(4n))

jQueryの:nth-セレクタの実装はCSS仕様に沿って定められているため、nの値は1から始まります。 :eq():evenのような他のセレクタでは、JavaScriptに沿って0から始まります。 3つの<li>を含む1つの>ul>が与えられた場合、 $('li:nth-last-of-type(1)')は3つ目、すなわち最後の<li>を選択します。

この使用方法に関する詳細については、 W3CのCSSの仕様 に記載されています。

デモ

マッチした各ulの最後から2番目のliを見つけ、文章を追記します。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. div { float:left; }
  6. span { color:blue; }
  7. </style>
  8. <script src="http://code.jquery.com/jquery-latest.js"></script>
  9. </head>
  10. <body>
  11. <div>
  12. <ul>
  13. <li>John</li>
  14. <li>Karl</li>
  15. <li>Adam</li>
  16. </ul>
  17. </div>
  18. <div>
  19. <ul>
  20. <li>Dan</li>
  21. </ul>
  22. </div>
  23. <div>
  24. <ul>
  25. <li>Dave</li>
  26. <li>Rick</li>
  27. <li>Timmy</li>
  28. <li>Gibson</li>
  29. </ul>
  30. </div>
  31. <script>$("ul li:nth-last-of-type(2)").append("<span> - 2nd to last!</span>");</script>
  32. </body>
  33. </html>

各ボタンがどのように作用するか確認してみてください。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. button { display:block; font-size:12px; width:100px; }
  6. div { float:left; margin:10px; font-size:10px;
  7. border:1px solid black; }
  8. span { color:blue; font-size:18px; }
  9. #inner { color:red; }
  10. td { width:50px; text-align:center; }
  11. </style>
  12. <script src="http://code.jquery.com/jquery-latest.js"></script>
  13. </head>
  14. <body>
  15. <div>
  16. <button>:nth-last-of-type(even)</button>
  17. <button>:nth-last-of-type(odd)</button>
  18. <button>:nth-last-of-type(3n)</button>
  19. <button>:nth-last-of-type(2)</button>
  20. </div>
  21. <div>
  22. <button>:nth-last-of-type(3n+1)</button>
  23. <button>:nth-last-of-type(3n+2)</button>
  24. </div>
  25. <div>
  26. <table>
  27. <tr><td>John</td></tr>
  28. <tr><td>Karl</td></tr>
  29. <tr><td>Brandon</td></tr>
  30. <tr><td>Benjamin</td></tr>
  31. </table>
  32. </div>
  33. <div>
  34. <table>
  35. <tr><td>Sam</td></tr>
  36. </table>
  37. </div>
  38. <div>
  39. <table>
  40. <tr><td>Glen</td></tr>
  41. <tr><td>Tane</td></tr>
  42. <tr><td>Ralph</td></tr>
  43. <tr><td>David</td></tr>
  44. <tr><td>Mike</td></tr>
  45. <tr><td>Dan</td></tr>
  46. </table>
  47. </div>
  48. <span>tr<span id="inner"></span></span>
  49. <script>
  50. $("button").click(function () {
  51. var str = $(this).text();
  52. $("tr").css("background", "white");
  53. $("tr" + str).css("background", "#ff0000");
  54. $("#inner").text(str);
  55. });
  56. </script>
  57. </body>
  58. </html>

 Back to top

© 2010 - 2017 STUDIO KINGDOM