Adrian Florescu
Adrian Florescu

Reputation: 4492

JS getElementsByTagName except the one with a specific class

I have this variable:

var _inputs = document.getElementsByTagName('input');

But I want to make a new variable that will select all inputs, except the inputs that have a specific class like ".nothis".

var _newinputs = document.getElementsByTagName('input') && document.getElementsByClass('!nothis');

Upvotes: 1

Views: 3687

Answers (4)

Mrchief
Mrchief

Reputation: 76218

Try this:

var _inputs = document.getElementsByTagName('input');
var filteredInputs = [];
var re = new RegExp('\\b' + 'nothis' + '\\b');  // or any other class name
for(var i=0; i<_inputs.length;i++) {
    if (!re.test(input.className)) {   // filter out by class name
        filteredInputs.push(_inputs[i]);
    }
}

Update: Added regex match to eliminate false positives as per suggestion from katspaugh

Upvotes: 3

Andrew D.
Andrew D.

Reputation: 8230

Try this code:

var _inputs = Array.prototype.filter.call(
                   document.getElementsByTagName("input"),
                   function(obj) { 
                     return obj.className.split(" ").indexOf("nothis")===-1;
                   });

Upvotes: 3

Gustav Barkefors
Gustav Barkefors

Reputation: 5086

In modern browsers you can do

var inputs = document.querySelectorAll('input:not(.nothis)');

Upvotes: 1

Related Questions