简体   繁体   中英

How do I click on a link without id

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

You need a CSS selector and the thenClick method here. Something like this should work:

casper.thenClick('#result_0 h3:first-child a');

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).

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM