I am trying to emulate a click on a basic link that appears like this with no id or class.
<a href="">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();
}
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();
}
Share
Improve this question
edited Oct 21, 2011 at 1:18
Dimitre Novatchev
243k27 gold badges303 silver badges436 bronze badges
asked Oct 20, 2011 at 15:43
bammabbammab
2,5637 gold badges26 silver badges28 bronze badges
2
|
2 Answers
Reset to default 10The 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();
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;
}
<a>
DOM elements, I don't think. – Pointy Commented Oct 20, 2011 at 15:46a
in fact has a value (maybe put awindow.alert(a);
before theclick()
call to verify) – Mike Christensen Commented Oct 20, 2011 at 15:48