Accessing elements by type in javascript

Saikios picture Saikios · May 5, 2011 · Viewed 142k times · Source

A while ago I was making some test in Javascript, and played with a code to get the text of all elements with a certain class, Now I was trying to make something like this but obtain all elements by a certain type, for example all elements type="text" Is there any way to do this in Javascript or should I use jquery?

var xx = document.getElementsByClassName("class");
for (i=0;i<xx.length;i++){
    var str=xx[i].innerHTML;
            alert(str);
}

Answer

karim79 picture karim79 · May 5, 2011

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();