How to make an analogy in jquery to handle an event per click on a specific class element. By type of example

js

for (var i=0; i<document.getElementsByClassName('blah')) { document.getElementsByClassName('blah')[i].addEventListener('click', function(){console.log('ok')}); } 

jq

 for (var i = 0; i < $('.blah').length; i++) { $('.blah')[i].click(function(){ console.log($('.blah')[i]); }); } 
  • If you are given an exhaustive answer, mark it as correct (the daw opposite the selected answer) - Mr. Black

2 answers 2

If it's quite simple, but to work on dynamically added elements, you can do this:

 var blah = document.body.querySelectorAll('.blah'); for (var x = 0; x < blah.length; x++) { blah[x].addEventListener("click", function() { console.log('javascript_' + this.innerHTML); }); } $('body').on('click', '.blah', function() { console.log('jquery_' + $(this).text()); }); 
 .blah { cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="blah">1</div> <div class="blah">2</div> <div class="blah">3</div> <div class="blah">4</div> <div class="blah">5</div> 

UPD. Added option on pure JS

  • Is there an option bypassing jquery? - Mr. Black
  • @Doofy, yes, now add - MasterAlex
  • Can shit code have a better way? - Mr. Black
  • How to select a specific item without this. console.log ($ ('. blah') [0]) does not give anything at all - ddeadlink
  • one
    @ddeadlink, $('.blah').eq(0) - Mr. Black

There is such an option

 Array.from(document.querySelectorAll('.qeqqe')).forEach(function(e, i) { e.onclick = function() { console.log(this.innerHTML, i); } }); 
 <div class='qeqqe'>one</div> <div class='qeqqe'>two</div> <div class='qeqqe'>tree</div> 

  • judging by the question, the author needed the implementation in jquery :) - MasterAlex
  • @MasterAlex, it means he got the answer =) $('.blah').on('click', function() {} - Mr. Black