Accessing elements by type in javascript

后端 未结 4 666
逝去的感伤
逝去的感伤 2020-12-25 09:51

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

相关标签:
4条回答
  • 2020-12-25 10:09

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

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

    Or

    var elements = $('input:text');
    
    0 讨论(0)
  • 2020-12-25 10:22

    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();
    
    0 讨论(0)
  • 2020-12-25 10:26
    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;
    }());
    
    0 讨论(0)
  • 2020-12-25 10:30

    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

    0 讨论(0)
提交回复
热议问题