Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByTagName Exclude Elements (Filter)

Tags:

javascript

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?

like image 673
Adrian Florescu Avatar asked Aug 04 '12 15:08

Adrian Florescu


1 Answers

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);
like image 97
micnic Avatar answered Oct 08 '22 08:10

micnic