Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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);
    });
});

Solution 2:

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);

Solution 3:

You should analyze click event. Watch on the target and currentTarget properties.

jsfiddle

document.getElementById('test').addEventListener('click', function (event) {
    if (event.target !== event.currentTarget) {
        do something
    } else {
        don't do something
    }
});

Post a Comment for "Which Is The Vanilla Javascript Equivalent For .not() Of Jquery?"