bammab
bammab

Reputation: 2563

how to apply click() to a tag using javascript

I am trying to emulate a click on a basic link that appears like this with no id or class.

<a href="http://www.myebsite.com/service/playnow">Click to Start</a>

I have the following code but when i load the page to no click action is performed. What am I doing wrong?

    var a = document.evaluate( '//a[contains(@href, "playnow")]' ,document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
    if(a){
        a.click();
    }

Upvotes: 8

Views: 38851

Answers (2)

Mike Christensen
Mike Christensen

Reputation: 91618

Why your tag doesn't have an ID is strange, but I'll assume for some reason you can't control that. I don't think you can emulate a click through a "click" method, so perhaps try something like:

var a = document.evaluate( '//a[contains(@href, "playnow")]' ,document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
if(a){
   window.location.href = a.href;
}

Upvotes: 6

JaredPar
JaredPar

Reputation: 754763

The easiest way is to add an id to the anchor tag and then invoke the click function on the DOM element

HTML:

<a id="theAnchor" href="http://www.myebsite.com/service/playnow">Click to Start</a>

JavaScript:

document.getElementById('theAnchor').click();

Upvotes: 10

Related Questions