问题
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