简体   繁体   中英

Calling an Onclick() function without clicking?

A websites Button isn't rendering on my browser. I know it's there, when I'm in the view source I still see the button, and the onclick function. Can I still call this function by passing the url the function? Or in the console?

Even if it's not an onclick, is it possible to call functions by either URL or Console?

You can click any DOM element by selecting it and calling the click() function.

document.getElementById("yourElementId").click();

Works with Jquery as well.

$(selector).click();

To accomplish this, you can use the following line:

document.getElementById("element_id").click()

According to MDN , this simulates a full click on the element, including all it entails:

When click is used with elements that support it (eg one of the types listed above), it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an element to initiate navigation as if a real mouse-click had been received.


Alternatively, you can use jQuery to accomplish the same thing:

$("#trigger").click();

Here is the simplest way:

function fireClick(node){
    if ( document.createEvent ) {
        var evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, false);
        node.dispatchEvent(evt);    
    } else if( document.createEventObject ) {
        node.fireEvent('onclick') ; 
    } else if (typeof node.onclick == 'function' ) {
        node.onclick(); 
    }
}

So you can trigger the click event for an element like below:

fireClick(document.getElementById('id'));

Reference from here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM