There is jQuery code. How to write it in javascript?

$('body').on("click", "#rect", function() { var a = $(this).val(); alert(a); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <body> <button type="button" class="rect" id="rect" value="316">5445</button> </body> 

    3 answers 3

    For example:

     document.addEventListener("click", function(e) { if (e.target.id == 'rect') console.log(e.target.value); }) 
     <body> <button type="button" class="rect" id="rect" value="316">5445</button> </body> 

    PS: I clicked on the document, you better attach it to the element in which your button will appear

    Here is an example with your comment code:

     var fox = document.querySelector("body"); setTimeout(function() { fox.innerHTML += '<button type="button" class="rect" id="rect" value="316">5445</button>'; }, 2000); fox.addEventListener("click", function(e) { console.log(e.target); if (e.target.id == 'rect') alert(4); }); 
     <body> </body> 

    • there are no errors but console.log doesn't work - Vadim
    • @Vadim Apparently you did something wrong - Rostyslav Kuzmovych 6:36 pm
    • var fox = document.querySelector ("body"); fox.addEventListener ("click", function (e) {if (e.target.id == 'rect') alert (4);}); - Vadim
     document.body.addEventListener('click', () => { if (this.querySelector('#rect')) alert(this.querySelector('#rect').value); }) 

       var el = document.getElementById("rect"); el.addEventListener("click",function() { var a = this.value; alert(a); }) 
       <body> <button type="button" class="rect" id="rect" value="316">5445</button> </body> 

      • This element at the very beginning in the dom is not there, it appears under a certain condition, so if I insert something into the function ok but it does not work outside - Vadim
      • @Vadim then you need to run this code after this element is added. - Dmitri Polyanin
      • so jquery works outside and everything is ok here is the problem - Vadim
      • This code only works in the function - Vadim
      • @Vadim there already answered you. - Dmitry Polyanin