0

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!

3 Answers 3

2

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);
  })
})
Sign up to request clarification or add additional context in comments.

Comments

2

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>

5 Comments

Note that Array.from is quite new. You may also use Array.prototype.forEach.call
@Jonasw Nope, it's not quite new. ES6 is a standard, actually. I would rather say that using call on Array prototype functions is deprecated.
@Jonasw Feel free to make your own answer. That's my coding style which I recommend.
@Kinduser Array.from is not supported in IE; many projects still need IE support.
@RyanZim IE is not a browser, actually. Anyways you can just use old for loop instead of forEach, so Array.from won't be needed.
1

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'

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.