How to click a link using javascript
I am trying to click on the following link in the html page but having difficulty.
I need to get the elementbyclassname of the main div and click on the second div element, here is the HTML of the page I want to click:
<div class="next-previous">
<a href="http://website.net/560339/1/">Previous </a>
<a href="http://website.net/560339/2/">Next</a>
</div>
Here is the Javascript that I have tried so far.
var nextlink = document.getElementsByClassName('next-previous');
nextlink[0].click();
source to share
You click on div
that doesn't work. You need to click a
.
Replace nextlink[0].click()
with nextlink[0].lastElementChild.click()
and it should work.
Demo (replaceable target links for alerts):
var nextlink = document.getElementsByClassName('next-previous');
nextlink[0].lastElementChild.click();
<div class="next-previous">
<a href="javascript:alert('Previous')">Previous </a>
<a href="javascript:alert('Next')">Next</a>
</div>
source to share
I'm confused. Your question is tagged jQuery, but you are using Vanilla.JS.
Anyway:
JQuery
$("div.next-previous>a:nth-of-type(2)").click()
// clicks on second <a>
Vanilla.JS
document.getElementsByClassName('next-previous')[0].children[1].click()
//does the same
//gets an array of elements with the class 'next-previous', takes the first, then takes the second child and clicks on it
source to share
you can use
$('.next-previous a').trigger('click');
Or even this will work
$('.next-previous').find('a').trigger('click');
As I see, you have multiple tags <a>
in <div>
, so I suggest applying a <a>
unique class
or to each tag id
. This way it will be easier to reference links in js / jquery otherwise you will need to use attributes ElementChild
.
source to share
My humble contribution, blind shot, although your question is not clear:
var clsA = document.querySelectorAll('.cls > a');
clsA[0].addEventListener('click', function (ev) {
var span;
ev.preventDefault();
span = document.createElement('span');
span.textContent = ' allo';
this.parentNode.appendChild(span);
});
<div class="cls">
<a href="#">here</a>
</div>
source to share
Stream this blog post. I think this will help you understand why the anchor is not hitting javascript. http://blog.stchur.com/2010/01/15/programmatically-clicking-a-link-in-javascript/
source to share
you need to use :nth-child()
to get the desired child. as
var nextlink = document.document.querySelectorAll('.next-previous:nth-child(2)').click(); // click the second link
var nextlink = document.document.querySelectorAll('.next-previous:nth-child(2)').click();
<div class="next-previous"> <a href="http://website.net/560339/1/>Previous</a>
<a href="http://website.net/560339/2/">Next</a>
</div>
source to share