0

Possible Duplicate:
Is it possible to trigger a link's (or any element's) click event through JavaScript?

How to click an "a href link" dynamically using JavaScript

I am using this code to call JavaScript code:

<a href="javascript:void(0)" onclick="javascript:execute();">

I want to click this link automatically.

is it possible with javascript?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sree
  • 1
  • 1
  • 1
  • 1

2 Answers2

1

Give your href link some id then use this: document.getElementById('id').click();

Shehzad Bilal
  • 2,535
  • 2
  • 18
  • 27
  • If it's a link, it can also be accessed as `document.links.id`. Only if you like to type less of course. :-) – RobG Jul 05 '12 at 11:09
  • @RobG - I can't find that `id` is a method or property of the `link` object: http://help.dottoro.com/ljrrevii.php#links . The closest I've found is `document.links.item('id')` I've tried something like: `document.links[0].click` and `document.links.item(0).click;`, with no luck. Can you provide any more info or possibly an answer with examples – Kevin Fegan Oct 28 '16 at 21:41
  • @KevinFegan—the *links* collection is explained [*on MDN*](https://developer.mozilla.org/en-US/docs/Web/API/Document/links) with links to relevant standards. Using the ID is included in the WHATWG specification for [*collections*](https://dom.spec.whatwg.org/#interface-htmlcollection) as `element = collection[name]`. A link with ID *foo* might be `document.links.foo` or `document.links['foo']` or `document.links.namedItem('foo')`, etc. – RobG Oct 30 '16 at 23:23
  • @RobG - Those links were very helpful. After a quick look, I did manage to find `document.links['foo']` and `document.links.namedItem('foo')`, but not `document.links.foo`. I'll do some more looking and perhaps some experimenting. Thanks. – Kevin Fegan Nov 03 '16 at 12:26
0

An A element is intended to be used as either a link or anchor, if you don't want either of those you should use some other element. In this case, a button seems the better option. Then users have a visual clue that the element will do something but not navigate anywhere.

You can dispatch an event on the element (see xdazz's comment), or if you don't want the click to bubble you can just call the handler and set the element as this:

element.onclick.call(element);
RobG
  • 142,382
  • 31
  • 172
  • 209