简体   繁体   中英

Javascript equivalent of jQuery onclick

How should i construct my code to get the effect of this jQuery

var divQuery = $('.html5gallery-thumbs-0').children();
    divQuery.on('click', function () {...}

I thought it is something like this :

 var divQuery = document.getELementsByClassName('html5gallery-thumbs-0');
        divQuery.onclick = function (elem) {
//this.style.display = 'none'
// OR
//elem.style.display = 'none'

}

Element should reference to the clicket object right? Or it should be the key word this . I want to learn javascript because jQuery is only library after all. Thank you in advance!

Just catch the parent with querySelector and get it's children with children function. Then - iterate over it and bind listener.

 const divQuery = document.querySelector('.a'); Array.from(divQuery.children).forEach(v => { return v.addEventListener('click', function() { console.log(this.textContent); }) }) 
 <div class="a"> <div>child1</div> <div>child2</div> </div> 

Extending kind users answer with two other approaches:

Using the latest and greatest JS features:

const divQuery = document.querySelector('.a');
divQuery.childNodes.forEach(v => {
  v.addEventListener('click', function() {
    console.log(this.textContent);
   })
 });

And a really old one (which supports IE and other older browsers):

const divQuery = document.getElementsByClassName('a')[0];
  [].forEach.call(divQuery.children, function(v){
     v.addEventListener('click', function() {
     console.log(this.textContent);
  })
})

what you are doing is almost correct. But when you are finding elements by class it gives you a collection of object. So, first select the index then assign the onclick function. Like below.

var divQuery = document.getELementsByClassName('html5gallery-thumbs-0');
        divQuery[0].onclick = function (elem) {
//this.style.display = 'none'
// OR
//elem.style.display = 'none'

}

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