Reputation: 4047
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().
Upvotes: 6
Views: 9443
Reputation: 117
You should analyze click event. Watch on the target and currentTarget properties.
document.getElementById('test').addEventListener('click', function (event) {
if (event.target !== event.currentTarget) {
do something
} else {
don't do something
}
});
Upvotes: 1
Reputation: 2649
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);
});
});
Upvotes: 6
Reputation: 166001
The closest equivalent is probably Array.prototype.filter
which allows you to test each element of an array with a function:
var elementToExclude = something;
arrayOfElements.filter(function (elem) {
return elem !== elementToExclude;
}).forEach(doSomething);
Upvotes: 7