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?
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?
Share Improve this question edited Aug 4, 2012 at 15:27 j08691 208k32 gold badges269 silver badges280 bronze badges asked Aug 4, 2012 at 15:26 Adrian FlorescuAdrian Florescu 4,50210 gold badges52 silver badges77 bronze badges 6-
4
Iterate over the elements and put the ones you want to keep in an array. If
querySelectorAll
is available in the browsers your code is supposed to run, I'd rather use that. – Felix Kling Commented Aug 4, 2012 at 15:28 - @felix-kling I want something like this: var inputs = document.getElementsByTagName("input:not('.existent')"); I need to use this code on older browsers as well. – Adrian Florescu Commented Aug 4, 2012 at 15:40
- Yes, that won't work. That's why I said you have to iterate over the elements, test each of them if they have that class and if not, keep it (put it in an other array). – Felix Kling Commented Aug 4, 2012 at 15:41
- @Florescu, support CSS selectors, support older browsers, do not use jQuery. Choose any two. – Frédéric Hamidi Commented Aug 4, 2012 at 15:42
- @FrédéricHamidi :) I don't use regular JavaScript that is why I am asking this question. With jQuery is simple $('inputs').not('.exists') and it will give me the array, but this script is done by someone else and I need to find a fix for this... – Adrian Florescu Commented Aug 4, 2012 at 15:49
1 Answer
Reset to default 13This 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);