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();
}
You can call a function in 2 ways using the href or onclick attribute in the HTML tag.
Method 1: Using the click() method: The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.
Instead of embedding html into javascript, you could make a bunch of predefined javascript functions and then use them outside of the script tags. For example, here's how to display a picture while still using the javascript functions. Save this answer.
The <a> tag defines a hyperlink, which is used to link from one page to another. The most important attribute of the <a> element is the href attribute, which indicates the link's destination. By default, links will appear as follows in all browsers: An unvisited link is underlined and blue.
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;
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With