Simulate click GMail div button with JS

I want to simulate a click on a GMail COMPOSE button using JS without jQuery.

Here is the button:

<div class="TI J-J5-Ji TI-KE L3" role="button" tabindex="0" gh="cm" style="-webkit-user-select: none;">COMPOSE</div> 

Here is my js:

 var element = document.getElementsByClassName('TI-KE')[0]; element.click(); 

Result: undefined in all browsers

Image: http://i.imgur.com/4IX9DZX.png

Already tried:

 var event = document.createEvent("MouseEvent"); event.initEvent("click",true,true); var element=document.getElementsByClassName("TI-KE")[0]; element.dispatchEvent(event); 

Result: true . But nothing happens.

Image: http://i.imgur.com/pwVqukP.png

+6
source share
2 answers

Two days later, I finally got an answer!

This button listens for mouseDown and mouseUP events. Work code:

 var down = new MouseEvent('mousedown'); var up = new MouseEvent('mouseup'); var elem = document.getElementsByClassName("TI-KE")[0]; elem.dispatchEvent(down); elem.dispatchEvent(up); 
+7
source

The getElementsByClassName(classString) function will return elements with the class exactly the string you pass to it. Try using querySelector like

 document.querySelector(".TI-KE"); 

This will return the first item with the TI-KE class. If you want ALL elements with this class, call the querySelectorAll function instead

-1
source

Source: https://habr.com/ru/post/982380/


All Articles