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>
Use the querySelector() method to get the nth child of an element, e.g. document. querySelector('#parent :nth-child(3)') . The :nth-child pseudo class returns the element that matches the provided position.
Definition and Usage The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
To get the nth-child of an element using the querySelector method, pass the :nth-child() pseudo-class as a parameter to the method, e.g. document. querySelector('#parent :nth-child(1)') . The nth-child pseudo-class returns the element that matches the specified position.
1. nth - ADJECTIVE - Mathematics Denoting an unspecified member of a series of numbers or enumerated items. '
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With