Home > Software design >  Jquery to javascript - click() working with z document.getElementById
Jquery to javascript - click() working with z document.getElementById

Time:01-12

There was a need to rewrite the code written with jquery into js. I have little js code on my site and I see no reason to include a library such as jquery.

This works (Jquery):

$('#prime').click(function() {
  myFuction();
});

function myFunction() {
  $('.prime').toggleClass('fa-message');
  $('.prime').toggleClass('fa-xmark');
}

This doesn't:

document.addEventListener('DOMContentLoaded',function(){

    document.getElementById("prime").click(function() {
          myFuction();
        });
        
        function myFunction() {
          document.getElementByClassName("prime").classList.toggle("fa-message");
          document.getElementByClassName("prime").classList.toggle("fa-xmark");
        }
}

Why?

I tried to rewrite the code jquery to js and something didn't work out.

CodePudding user response:

The way you add an onclick event to a DOM element in vanilla javascript is using the following syntax:

object.onclick = function() {myScript};

for for your case it would look like:

document.getElementById("prime").onclick = function() {  myFuction(); };

Here is some supporting documentation to help:

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

  • Related