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().
In jQuery, you can listen to events for dynamically added elements using the on() function. The equivalent in JavaScript is addEventListener() function.
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.
The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll() , which, just like with jQuery, you can call with a CSS selector.
"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."
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With