Accessing elements by type in JavaScript

JavascriptTypesElementDocument

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - 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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

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

Or

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

Solution 4 - Javascript

var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
    var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
    for (;i<l;i++) {
        if (elems[i].type.toLowerCase() === "text") {
            ret.push(elems[i]);
        }
    }
    
    return ret;
}());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaikiosView Question on Stackoverflow
Solution 1 - JavascriptMicView Answer on Stackoverflow
Solution 2 - Javascriptkarim79View Answer on Stackoverflow
Solution 3 - JavascriptMatthew AbbottView Answer on Stackoverflow
Solution 4 - JavascriptSamuli HakoniemiView Answer on Stackoverflow