Abdul_Kuddus
Abdul_Kuddus

Reputation: 23

what is the difference between $("#mybtn") and document.getElementById("mybtn")

I have a HTML code below:

<button id="mybtn">Click<button>

I have written two script for this code

script One:

<script>
    $("#mybtn").click(function(){
        console.log('clicked')
    });
</script>

script two:

<script>
    document.getElementById('mybtn').click(function(){
        console.log('clicked'):
    });
</script>

Now the issue is whenever I reload the page with the first script, it's okay. I have to click on the button and it prints "clicked".

But when I reload the page with the second script it automatically clicks the button(the clik event happens right after the page is reloaded) and prints "clicked".

what is the reason behind this ???

Upvotes: 1

Views: 508

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

$(...) returns a jQuery collection. .click(someFunction) on a jQuery collection attaches a click handler.

In contrast, document.getElementById('mybtn') returns an HTMLElement. HTMLElement.prototype.click is a function which, when invoked, "clicks" the button (invoking associated handlers, among other things). So, your second script's .click() results in the first script's click handler running. (Your second script's function is not used; HTMLElement.prototype.click does not do anything with any arguments it may receive)

If you want to attach a listener via JS and not via jQuery, do:

document.getElementById('mybtn').addEventListener('click', () => {
    console.log('clicked');
});

Upvotes: 4

Related Questions