Adrian Florescu
Adrian Florescu

Reputation: 4492

getElementsByTagName Exclude Elements (Filter)

I have a JavaScript selector like this:

var inputs = document.getElementsByTagName("input");

This works great except that I want to filter out some inputs (the ones with the class of "exists")

How can I do this without jQuery?

Upvotes: 10

Views: 11096

Answers (1)

micnic
micnic

Reputation: 11245

This is what you need:

var inputs = document.getElementsByTagName("input");
var neededElements = [];
for (var i = 0, length = inputs.length; i < length; i++) {
    if (inputs[i].className.indexOf('exists') >= 0) {
        neededElements.push(inputs[i]);
    }
}

Or, in short (as provided by knee-cola below):

let neededElements = [].filter.call(document.getElementsByTagName('input'), el => el.className.indexOf('exists') >= 0);

Upvotes: 13

Related Questions