1

I m trying to automated a web application from javascript. I able to locate the control, however I m unable to click on the control, it does perform any action.

I have tried to get li as well as p element (able get the correct element), but when I use click() method it doesn't work.(no exception thrown and no actions done on screen as well.)

I have tried the following codes which has no effect on the screen.

      var elem =   document.getElementsByClassName('class2');
      elem .click();
   

      var elem = document.getElementById('id1');
         elem .click();
 

       var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0, false, false, false, false, 0, null);
    document.getElementById("id1").dispatchEvent(evt);
<li class="class1" id="id1">
       <p class="class2">
       <span class="class3"></span>
       Export Excel</p>
       </li>

I have also tried to get the type of(elem.onclick) which returned undefined. 

Also tried fireEvent which throws exception.(Object doesn't support property or method 'fireevent').

I expect to click the element which will in turn open save as dialog. as we get when we click on the element. Please help me to find which ways to click on the element.

4
  • Try mousedown, mouseup, mouseover events Commented Jul 24, 2019 at 12:47
  • I have created a snippet for you and the console is throwing errors. Commented Jul 24, 2019 at 12:47
  • With non-clickable elements you'll need onclick() instead of click(). Found this answer, check this out: https://stackoverflow.com/questions/6367339/trigger-a-button-click-from-a-non-button-element Commented Jul 24, 2019 at 12:50
  • I have tried onclick as well it throws exception as object expected. Commented Jul 24, 2019 at 12:58

1 Answer 1

1

.getElementsByClassName() return an array-like object of all child elements which have all of the given class names. .click() is work with one element. So you have to decide with which of element (if exists) to use.

var elem = document.getElementsByClassName('class2');
var barEl = document.getElementsByClassName('bar');

function foo(ev) {
  console.log(ev);
}

//use the first (if there is a first) of elem
if (elem.length) {
  elem[0].addEventListener('click', foo); 
  elem[0].click(); 
}
// use all of barEl 
// i prefer for loop (browser compatibility)
var i = 0
for ( i; i < barEl.length; i++) {
   barEl[i].addEventListener('click', foo); 
}

It is not necessary to use ev in foo - just for example.

Sign up to request clarification or add additional context in comments.

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.