Reputation: 2563
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
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
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