Javascript 在javascript中按类型访问元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5897122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:25:04  来源:igfitidea点击:

Accessing elements by type in javascript

javascripttypeselementdocument

提问by Saikios

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?

前段时间我在 Javascript 中进行了一些测试,并使用了一段代码来获取某个类的所有元素的文本,现在我正在尝试制作这样的东西,但获取某种类型的所有元素,例如所有元素type="text" 有什么办法可以在 Javascript 中做到这一点,还是应该使用 jquery?

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

回答by karim79

In plain-old JavaScript you can do this:

在普通的 JavaScript 中,你可以这样做:

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:

在 jQuery 中,您只需执行以下操作:

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

回答by Mic

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

“最近”意味着不是 IE6 和 IE7

回答by Samuli Hakoniemi

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

回答by Matthew Abbott

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

sizzle 选择器引擎(JQuery 的动力)完美地为此做好了准备:

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

Or

或者

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