views:

1380

answers:

3

Suppose I load a webpage which contains the following anchor:

<a class="someClass" href="#" onClick="gotoPage('http://somepage.org')"&gt;Link&lt;/a&gt;

What I want is: as soon as the page is loaded, I want to generate onClick for this anchor which has text as "Link".

Note that the anchor does not contains any id or name associated with it. Thus document.getelementbyid or document.getelementbyname will not work.

+2  A: 

Here is what people seem to do to be able to generically trigger a click event in Firefox. They extend the HTMLAnchorElement prototype with a click() function, like so:

HTMLAnchorElement.prototype.click = function() {
  var evt = this.ownerDocument.createEvent('MouseEvents');
  evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
  this.dispatchEvent(evt);
}

See MDC for initMouseEvent().

If you have jQuery, you might also check out trigger().

Tomalak
+2  A: 

As you're using Greasemonkey you should be able to use XPath to select the link in question using one of it's HTML attributes:

http://diveintogreasemonkey.org/patterns/match-attribute.html

Ian Oxley
A: 

The solution (which Tomalak linked to) from https://developer.mozilla.org/en/DOM/event.initMouseEvent worked great for me, and it doesn't require prototype or jquery.

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}
neu242