Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
like image 665
bammab Avatar asked Oct 20 '11 15:10

bammab


People also ask

Can you use onclick on a tag?

You can call a function in 2 ways using the href or onclick attribute in the HTML tag.

How do you click using Javascript?

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.

Can you use tags in Javascript?

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.

What is anchor tag Javascript?

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.


2 Answers

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;
}
like image 95
Mike Christensen Avatar answered Oct 05 '22 23:10

Mike Christensen


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();
like image 25
JaredPar Avatar answered Oct 05 '22 23:10

JaredPar