DEV Community

ChuangWANG
ChuangWANG

Posted on

Generate clicking event in js

Get DOM element is javascript

document.getElementById()
document.getElementsByName()
document.getElementsByTagName()
document.getElementsByClassName()
// Parameter same to parameter css selector
document.querySelector()  
document.querySelectorAll()
// Specific for getting html element
document.documentElement()  
// Specific for getting body element
document.body()  
Enter fullscreen mode Exit fullscreen mode

Generate clicking event in js

<html>  
    <head>  
        <title>usually function</title>  
    </head>  
    <script>  

function load(){  
    //下面两种方法效果是一样的  
    document.getElementById("target").onclick();  
    document.getElementById("target").click();  
}  

function test(){  
    alert("test");  
}  

</script>  
    <body onload="load()">  
        <button id="target" onclick="test()">test</button>  
    </body>  
<html> 
Enter fullscreen mode Exit fullscreen mode

Remark.

btnObj.click() is to actually click the button with the program, triggering the button's onclick() event

btnObj.onclick() simply calls the method pointed to by btnObj's onclick, which is just a method call and does not trigger the event.

Top comments (0)