john
john

Reputation: 35420

Without using jQuery, how can I get inputs by type?

I know I can call:

document.getElementsByTagName("input");

Do I need to loop through and check the attributes for type == "text" ?

I know jQuery has input[type="text"]. Is there any plain JavaScript way to achieve this?

Upvotes: 2

Views: 9937

Answers (4)

Free Consulting
Free Consulting

Reputation: 4412

It is actually a sizzlejs-specific not jquery itself. And yes, dropping jquery is for good. DOM0 collections will perform this task in the best way:

for ( var i = 0; i < document.forms.length; i++ )
  for ( var j = 0; j < document.form[i].elements.length; j++ )
    /* have to do case-insensitive match to support any DOCTYPE */
    if ( document.form[i].elements[j].type.toUpperCase() == 'TEXT' )
      document.form[i].elements[j] = 'HAI!'; 
      /* done! */

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360016

You've got it mostly correct - unless the code is running in a browser which supports querySelectorAll. Here's the cross-browser code:

var textInputs;
if (document.querySelectorAll)
{
    textInputs = document.querySelectorAll('input[type=text]');
}
else
{
    textInputs = [];
    var unfiltered = document.getElementsByTagName("input"),
        i = unfiltered.length,
        input;
    while(i--)
    {
        input = unfiltered[i];
        if (!input.type || input.type === 'text')
        {
            textInputs.push(input);
        }
    }
}

N.B. in the else case, I check for the truthiness of input.type in case the input looks like this:

<input />

in which case it defaults type="text". I only included this because I'm not 100% sure if every browser will return "text" when the attribute is left off. For the record, at least Chrome does. http://jsfiddle.net/mattball/jJsjn/

Upvotes: 8

Craig White
Craig White

Reputation: 14022

This is how you can do it :)

var elements = document.getElementsByTagName('input')
for(var e in elements)
{
    if(e.type == "text")
    {
    }
}

Upvotes: 2

Phil
Phil

Reputation: 165059

If it's available to you, you can use the Selectors API.

Upvotes: 1

Related Questions