1

I need to call a click operation in native javascript. I got the following element:

<svg class="pull-right svg-cross ng-isolate-scope" xmlns="http://www.w3.org/2000/svg" data-svg-icon="" icon="cross" ng-click="dismissBanner()">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#svg-cross"></use>
</svg>

I seems to be a website that uses angular. I would like to click on the element such that the function dismissBanner() gets properly called. Therefore I tried the following:

document.getElementsByClassName('pull-right svg-cross ng-isolate-scope')[0].click(); 

and

document.getElementsByClassName('pull-right svg-cross ng-isolate-scope')[0].onclick(); 

However, both attempts have failed. I get the error Uncaught TypeError: document.getElementsByClassName(...)[0].onclick is not a function(…).

I also called the dismissBanner(); function directly, however, then I get the error: Uncaught ReferenceError: dismissBanner is not defined(…)

How should I do that correctly?

2 Answers 2

2

It looks like this is the working approach:

angular.element('.svg-cross').trigger('click');

Source: How to trigger ng-click [AngularJS] programmatically

After chatting with the OP, we found that the version of Angular used is 1.3.17. For this version, the correct approach to trigger a click is this:

var el = document.getElementsByClassName('pull-right svg-cross ng-isolate-scope')[0];
angular.element(el).triggerHandler('click');
Sign up to request clarification or add additional context in comments.

5 Comments

Hmm, I'm getting the following error, when calling this: Uncaught Error: [jqLite:nosel] http://errors.angularjs.org/1.3.17/jqLite/nosel(…)
@toom I just updated the answer to include only one class name, as well as changing triggerHandler to trigger. Could you try it one more time?
I tried your new suggestion. Unfortunately it causes an error.
I posted the error in the first comment. I tried it in Chrome. I even get an error by just calling angular.element('.svg-cross')
1

You can emulate a click by dispatching an event to the element. There's an object for that (Event), but the constructor is not supported in IE. You can overcome that with a deprecated API (document.createEvent):

function mock() {
  var evt;
  try {
    evt = new Event('click');
  }
  catch(e) {
    evt = document.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  }

  document.getElementById('trgt').dispatchEvent(evt);
}
<div id="trgt" onclick="alert('clicked!')">Don't click me</div>
<div onclick="mock()">Click me!</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.