Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth child in javascript

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>
like image 782
User 1278 Avatar asked Mar 01 '17 09:03

User 1278


People also ask

How do you find the nth child?

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.

What is an nth child?

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.

How do you querySelector nth child?

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.

What does nth mean in Javascript?

1. nth - ADJECTIVE - Mathematics Denoting an unspecified member of a series of numbers or enumerated items. '


2 Answers

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>
like image 114
Rajesh Avatar answered Sep 29 '22 18:09

Rajesh


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

like image 27
Dherya Avatar answered Sep 29 '22 19:09

Dherya