0

I am trying to write Javascript code into the console in chrome that will click a link on a page. The code I am using is

document.getElementById("id_name").getElementsByTagName("a").dispatchEvent(MouseEvent.ClICK)

And gives me this error: TypeError: undefined is not a function. Am I doing this the right way? And what is the correct way to simulate a click event on an HTML element? Also I am trying to do this without jQuery.

azrosen92
  • 8,357
  • 4
  • 26
  • 45
  • 2
    Duplicate of [what's the equivalent of jquery's 'trigger' method without jquery?](http://stackoverflow.com/questions/5658849/whats-the-equivalent-of-jquerys-trigger-method-without-jquery) or the first link when you type your question title into Google [How to simulate mouse click using Javascript?](http://stackoverflow.com/questions/6157929/how-to-simulate-mouse-click-using-javascript). – Joe May 02 '14 at 18:57
  • 1
    Your specific error comes from the fact that you're trying to call `.dispatchEvent()` on a collection of elements instead of on an actual element. – cookie monster May 13 '14 at 18:39

2 Answers2

2

Well I can't take credit for the code, but when googling around for an answer to this question I stumbled across a jsFiddle where someone's demoed this: http://jsfiddle.net/roine/wyh9r/

function fire( elem, type ) {

  var evt = elem.createEvent("Events");

  evt.initEvent( type, true, true, window, 1);

  elem.dispatchEvent(evt);

}

document.addEventListener( "plop", function() {
   console.log( "Fired a synthetic click event" );
}, false );


fire( document, "plop" );

So you'd just replace "plop" with "click" to simulate a click event.

Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
1

All you have to do is get the element and call the onclick() method.

document.getElementById("id_name").onclick();
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
  • I don't, but that was not OPs question. – John Hartsock May 02 '14 at 19:03
  • 2
    OMG! your Just trolling. Again that was not OPs question. Instead of questioning another's answer comment with suggestion. He is not writing this in to the web page but instead testing from Chrome's debug console. Yes it may throw an error, but I am simply answering his original question. – John Hartsock May 02 '14 at 19:06
  • This answer is incorrect as it doesn't do anything like what the question is asking. And no, it isn't trolling to point out what's wrong with an answer. Comments that politely correct an incorrect answer are not examples of trolling and should not be flagged and removed. – cookie monster May 13 '14 at 18:15