admin管理员组

文章数量:1291601

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

Here is button:

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

Here is my js:

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

Result:undefined in all browsers

Image: .png

Already tried that:

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

Result:true. But nothing happens.

Image: .png

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

Here is button:

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

Here is my js:

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

Result:undefined in all browsers

Image: https://i.sstatic/Mkscf.png

Already tried that:

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

Result:true. But nothing happens.

Image: https://i.sstatic/H3KSH.png

Share Improve this question edited Feb 12, 2015 at 15:02 Mikolaytis asked Feb 12, 2015 at 12:24 MikolaytisMikolaytis 9621 gold badge14 silver badges27 bronze badges 3
  • Try this: stackoverflow./a/11765093/4506790 – Deurco Commented Feb 12, 2015 at 14:48
  • don't working. Returns true. But nothing happens. Result image: i.imgur./pwVqukP.png – Mikolaytis Commented Feb 12, 2015 at 15:02
  • I have found this post stackoverflow./a/52549234 and that works for me! – Liam Ray Commented Sep 3, 2021 at 18:24
Add a ment  | 

3 Answers 3

Reset to default 12

After two days i am finally got an answer!

That button listens mouseDown and mouseUP events. Working code:

var down = new MouseEvent('mousedown');
var up = new MouseEvent('mouseup');
var elem = document.getElementsByClassName("T-I-KE")[0];
elem.dispatchEvent(down);
elem.dispatchEvent(up);

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

document.querySelector(".T-I-KE");

That will return the first element with the class T-I-KE. If you want ALL the elementes with that class, call the function querySelectorAll instead

function click(tagNode) {
    const down = new MouseEvent('mousedown', {
        bubbles: true
    });
    const up = new MouseEvent('mouseup', {
        bubbles: true
    });
    tagNode.dispatchEvent(down);
    tagNode.dispatchEvent(up);
}

本文标签: javascriptSimulate click on GMail div button with JSStack Overflow