Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the vanilla javascript equivalent for .not() of jQuery?

I'm trying to create a loop which adds a class to a list. I wish this class to be added on all the elements except the element which is being clicked. I found the following on the internet:

$('.elements').click(function(){
     $('.elements').not(this).each(function(){
         // do something
     });
})

Is there an equivalent to vanilla javascript? I cannot find the conversion from .not().

like image 918
Daniel Ramirez-Escudero Avatar asked Sep 24 '14 09:09

Daniel Ramirez-Escudero


People also ask

What is the jQuery equivalent for on () of JavaScript?

In jQuery, you can listen to events for dynamically added elements using the on() function. The equivalent in JavaScript is addEventListener() function.

Is jQuery vanilla JavaScript?

Vanilla JS helped the developers in creating dynamic websites. Then came jQuery, a library of tools created by developers around the world, using Javascript. In simple words, jQuery is a lightweight and easy to use JavaScript library that helps in creating complex functionalities with few lines of coding.

What is equivalent to jQuery?

The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll() , which, just like with jQuery, you can call with a CSS selector.

Is vanilla JavaScript JavaScript?

"VanillaJS is a name to refer to using plain JavaScript without any additional libraries like jQuery back in the days. People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries."


1 Answers

The vanilla version of the full code you posted would be something like this. Quite verbose TBH without having the helper to add a click listener to each el.

var els = document.querySelectorAll('.elements');
[].forEach.call(els, function(el, i, els) {
    el.addEventListener('click', function() {
        [].forEach.call(els, function(el) {
            if(el !== this) {
                // do something
            }
        }, this);
    });
});
like image 106
imcg Avatar answered Sep 30 '22 19:09

imcg