Accessing elements by type in JavaScript Accessing elements by type in JavaScript javascript javascript

Accessing elements by type in JavaScript


If you are lucky and need to care only for recent browsers, you can use:

document.querySelectorAll('input[type=text]')

"recent" means not IE6 and IE7


In plain-old JavaScript you can do this:

var inputs = document.getElementsByTagName('input');for(var i = 0; i < inputs.length; i++) {    if(inputs[i].type.toLowerCase() == 'text') {        alert(inputs[i].value);    }}

In jQuery, you would just do:

// select all inputs of type 'text' on the page$("input:text")// hide all text inputs which are descendants of div class="foo"$("div.foo input:text").hide();


The sizzle selector engine (what powers JQuery) is perfectly geared up for this:

var elements = $('input[type=text]');

Or

var elements = $('input:text');