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.

Krishna Prashatt
  • 631
  • 9
  • 18

1 Answers1

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.

Ivan Ganchev
  • 174
  • 2
  • 10