Sai*_*ios 38 javascript types document element
前一段时间我在Javascript中进行了一些测试,并使用代码来获取具有某个类的所有元素的文本,现在我试图制作这样的东西但是通过某种类型获取所有元素,例如所有元素type ="text"有没有办法在Javascript中执行此操作,还是应该使用jquery?
var xx = document.getElementsByClassName("class");
for (i=0;i<xx.length;i++){
var str=xx[i].innerHTML;
alert(str);
}
Run Code Online (Sandbox Code Playgroud)
kar*_*m79 62
在普通的JavaScript中,您可以这样做:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'text') {
alert(inputs[i].value);
}
}
Run Code Online (Sandbox Code Playgroud)
在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();
Run Code Online (Sandbox Code Playgroud)
Mic*_*Mic 59
如果您很幸运并且只需要关注最近的浏览器,您可以使用:
document.querySelectorAll('input[type=text]')
Run Code Online (Sandbox Code Playgroud)
"最近"意味着不是IE6和IE7