Search code examples
javascriptjqueryjquery-selectorsselectors-api

using javascript queryselectorall instead of jquery selector


I want to rewrite this jQuery in pure JavaScript:

var gallery1 = $('.gallery a');

gallery1.click(function(event){
    event.preventDefault();
    console.log('onclick');
});

After trying to figure it out I ended with something like this:

var gallery = document.querySelector('.gallery a');

gallery.onclick = function(event){
    event.preventDefault();
    console.log('onclick');
};

But it works only with the first anchor of the ul.

When I try to use querySelectorAll('.gallery a') it does nothing.

I`m new to JavaScript. Can someone help me to figure it out?

HTML

<ul class="gallery" id="gallery">
    <li class="">
        <a href="img/gallery/gallery1.jpg" class="" id="anchor">
            <img src="img/gallery/gallery1.jpg" alt="image 1" class="img">
        </a>
    </li>
    <li class="">
        <a href="img/gallery/gallery2.jpg" class="">
            <img src="img/gallery/gallery2.jpg" alt="image 1" class="img">
        </a>
    </li>
    <li class="">
        <a href="img/gallery/gallery3.jpg" class="">
            <img src="img/gallery/gallery3.jpg" alt="image 1" class="img">
        </a>
    </li>
    <li class="">
        <a href="img/gallery/gallery4.jpg" class="">
            <img src="img/gallery/gallery4.jpg" alt="image 1" class="img">
        </a>
    </li>
    <li class="">
        <a href="img/gallery/gallery5.jpg" class="">
            <img src="img/gallery/gallery5.jpg" alt="image 1" class="img">
        </a>
    </li>
</ul>

Solution

  • You need to handle the array-like nodelist from querySelectorAll():

    var gallery = document.querySelectorAll('.gallery a');
    
    gallery.forEach(function(item) {
      item.onclick = function(event){
        event.preventDefault();
        console.log('onclick');
      };
    });