简体   繁体   中英

Pure JavaScript alternative to jQuery's .not()

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

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

I'm looking to do that in JS

Modern browser do support a 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";
}

You could also use .filter() to exclude items in your array. You would use it like so (example from MDN):

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

It's supported in all modern browsers and IE9+. See Array.prototype.filter() on MDN for more information.

Unfortunately .filter() only works on Arrays so we have to do some extra manipulating to filter a 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]

See this jsFiddle for a working example.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM