nth child in javascript

北战南征 提交于 2021-02-18 22:26:05

问题


This is my jquery code.I need javascript code to select nth child.Is it possible to select nth child using javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
     $(document).ready(function(){
       $(".gl-testim-text p:nth-child(2)").click(function(){
          $(".gl-testim-text p:nth-child(3)").show();
       });
     });

 </script>

回答1:


As commented by @abhitalks, you can use querySelector() plus :nth-child() selector

var second = document.querySelector(".content a:nth-child(2)")
console.log(second)

var even = document.querySelectorAll(".content a:nth-child(2n)")
console.log(even)
<div class="content">
  <a href="google.com">Google</a>
  <a href="Facebook.com">Facebook</a>
  <a href="StackOverflow.com">StackOverflow</a>
  <a href="YouTube.com">YouTube</a>
  <a href="Example.com">Example</a>
  <a>blabla</a>
</div>



回答2:


Purely native and basic

var length =  document.body.childNodes.length;
var last_child_of_body = document.body.childNodes[length-1];

This is just an example for last child. You can use any parent instead of body for your purpose




回答3:


use .next() method. You can also try children traversal methods.



来源:https://stackoverflow.com/questions/42528100/nth-child-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!