Pure JavaScript alternative for jQuery.not ()

What will be the JS alternative .not()from jQuery? I have $(".form :input").not, but I need to pass this to pure JS. Is there any guide that could help me?

 var input = $(".form :input").not('button, [type="button"], [type="submit"]').on({
input: return
});

I want to do it in js

+4
source share
3 answers

The equivalent in plain JS would be something like this

var forms = document.querySelectorAll('.form'),
    inputs = [];

for (var i = forms.length; i--;) {
    var els = forms[i].querySelectorAll('input, textarea, select');

    for (var j = els.length; j--;) {
        if (els[j].type != 'button' && els[j].type != 'submit') {
            inputs.push(els[j]);
            els[j].addEventListener('input', cback, false);
        }
    }
}

function cback(event) {
    var b = [];

    for (var i = inputs.length; i--;) {
        if (!inputs[i].value.length) b.push(inputs[i]);
    }

    var l1 = b.length;
    var l2 = inputs.length;
    var top = document.querySelectorAll('.top');

    for (var j = top.length; j--;) {
        top[j].style.width = 100 - (l1 / l2) * 100 + "%";
    }
}

Fiddle

+3
source

You can also use .filter()to exclude elements in your array. You would use it like this (example from MDN):

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

It is supported in all modern browsers and IE9 +. See Array.prototype.filter () in MDN for more details .

, .filter() , NodeList.

HTML:

<ul>
    <li>1</li>
    <li>2</li>
    <li class="not-me">3</li>
    <li>4</li>
    <li>5</li>
</ul>

JavaScript:

var filter = Array.prototype.filter;

var excludeByClassName = function(className) {
    return function (element) {
        return element.className != className;
    };
};

var LIs = document.getElementsByTagName('li');
// [li, li, li.not-me, li, li]

var filteredLIs = filter.call(LIs, excludeByClassName('not-me'));
// [li, li, li, li]

. jsFiddle .

+3

A modern browser supports the NOT clause in querySelectorAll():

document.querySelectorAll(".form :input:not(...)");

Example ( jsFiddle ):

<div>This should be colored!</div>
<div>This should be colored!</div>
<div id="this-not">This must not colored!</div>
<div>This should be colored!</div>
<div>This should be colored!</div>
var matchedElements = document.querySelectorAll("div:not(#this-not)");
for (var i=0; i<matchedElements.length; i++) {
    matchedElements.item(i).style.backgroundColor = "red";
}
+2
source

Source: https://habr.com/ru/post/1540434/


All Articles