Forum Moderators: open
var mylink = document.getElementsByTagName("a");
This returns an array of all the anchors in the document, so to call the onclick event of the first anchor, you could call:
mylink[0].onclick();
But I have a feeling you don't mean that. Are you wanting to visit the URL as specified in the href attribute? Then you could try:
location.href = mylink[0].href;
If it's not a straight forward URL in the href attribute (it could be a call to a JavaScript function) then it's going to require a little more work. As far as I'm aware there is no direct way to simulate a user clicking on a link, without first parsing the element.
I have some local greasemonkey scripts, that are ment to assist in browsing the web and in some situations I'd want to be able to click automagically.
Unfortunately I can't assume, that links are all URLs, because lot of them are calling for inline, even generated javascript that is not accessible globally.
So if there is no way to simulate a click, then I'll go for parsing...
thanks-a-lot
As far as I'm aware there is no direct way to simulate a user clicking on a link, without first parsing the element.
Actually I could have been very wrong there... it looks like you can do it?! I've not tried it... would also need to check cross-browser compatibility if that is of concern.
Try simply:
document.getElementById('mylink').click() Check these threads (from a few years ago!):
[webmasterworld.com...]
[webmasterworld.com...]
Looks like click() method actually works for some browsers (IE at least) , but I was hoping to use it in Firefox greasemonkey scripts.
Javascript click() method is documented at least on javascriptkit.com under DOM Element methods - might it be IE-only feature and for security reasons not supported by others?