CodyMan
CodyMan

Reputation: 153

How to click last child link using javascript

I'm trying to click on the last anchor element of the class

Class name "g1-pagination pagelinks" Anchor Element "Next >"

here is my HTML

<div class="Next-buttons">
 <nav class="g1-pagination pagelinks">
  <ul>
   <li>
     <a href="http://buzztache.com/with-you/"><span>&lt; BACK</span></a>
   </li> 
   <li>
     <a href="http://buzztache.com/with-you/3/"><span>NEXT &gt;</span></a>
   </li>
  </ul>
 </nav>
</div>

here what I have tried so fare.

var nextlink = document.getElementsByClassName('g1-pagination pagelinks');
nextlink[0].lastElementChild.click();

Upvotes: 2

Views: 1219

Answers (2)

Donnie D&#39;Amato
Donnie D&#39;Amato

Reputation: 3940

I know you've selected an answer (and a very complete one at that) but I don't think you'll need to use .find(), you should be able to just target in one shot.

$('.Next-buttons li:last a:first')[0].click();

Also, just for some who might try, .trigger('click') doesn't work on anchor tags unless you've added a specific event to them. You'll always need to use [0].click() instead.

Upvotes: 1

Lost_In_Library
Lost_In_Library

Reputation: 3493

Can you try this;

$('.Next-buttons').find('li:last a:first')[0].click();

Info: https://api.jquery.com/last-selector/

Another way to do it ( bad way );

var link =  $('.Next-buttons').find('li:last a:first').attr('href');
window.location = link

Or pure js as ( Credits: @itsgoingdown );

nextlink[0].lastElementChild.getElementsByTagName('A')[0].click();

Upvotes: 4

Related Questions