Reputation: 876
I'm not experienced in javascript. I'm trying to write a function in CasperJS, which uses javascript.
I'm trying to click on a link from a search result page. The <a href>
tag does not have an id to it, but it is enclosed in a <h3 />
, which is enclosed in a <div id="some_id"/>
.
Essentially the code looks like this:
<div id="result_0">
<div />
<div />
<h3 class="...">
<a href="some_link">
.
.
</a>
</h3>
.
.
</div>
I want to know how to click that link in javascript.
I tried doing it like this:
document.getElementById('result_0').getElementsByTagName('div')[2].getElementsByTagName('a')[1].click();
But this doesn't seem to work. Can you guys help ?
Edit: Here is the link to my entire script: https://github.com/ctrl-shift-esc/randomamazonshopper/blob/master/myscript.js
Upvotes: 1
Views: 1824
Reputation: 11414
You need a CSS selector and the thenClick method here. Something like this should work:
casper.thenClick('#result_0 h3:first-child a');
Upvotes: 3
Reputation: 66389
You can use the ID of the div holding the <h3>
:
var oParentDiv = document.getElementById("some_id");
var arrHeaders = oParentDiv.getElementsByTagName("h3");
if (arrHeaders.length !== 1) {
alert("no header or more than one");
} else {
var oHeader = arrHeaders[0];
var arrLinks = oHeader.getElementsByTagName("a");
if (arrLinks .length !== 1) {
alert("no link or more than one");
} else {
var oLink = arrLinks[0];
oLink.click();
}
}
Upvotes: 2
Reputation: 150000
The following works for the html structure shown in the question (if you change the div's id from some_id
to result_0
):
document.getElementById('result_0').getElementsByTagName('h3')[0]
.getElementsByTagName('a')[0].click();
Demo (open the browser's JS console): http://jsfiddle.net/kyLXT/1/
Perhaps your code had the wrong indices in the square brackets?
Or you can do this to click the first link in the first h3 within the element with that id:
document.querySelector('#result_0 h3 a').click();
Or if you're concerned that there might not be a matching element:
var el = document.querySelector('#result_0 h3 a');
if (el)
el.click();
// optionally add an else here
Note that either way the code would need to be in a script block that appears after the elements in question and/or in a DOM ready or window onload event handler (the jsfiddle demo above put the code in an onload handler via the fiddle options on the left).
Upvotes: 2