识别输入标签的存在

时间:2014-07-11 18:30:57

标签: javascript html

我有这个场景...... 在一个网页中,我将有几个输入/文本框...有时2或有时3.这将根据我的需要显示/创建..但一旦点击按钮显示页面,我想知道有多少输入标签是可用的..带有id我可能填充...

我是否可以通过id识别输入框是否可用。如果它不存在,我不希望突然停止pgm。

我在我的代码中使用html,css3和javascript(php是服务器编码)。

希望很清楚。如果没有,请告诉我。 提前谢谢!

1 个答案:

答案 0 :(得分:1)

  

我想知道有多少输入标签可用

您可以使用getElementsByTagName了解是否有<input>个标签。 getElementsByTagName返回一个类似数组的结构(NodeList?)并且有一个length属性来知道检索了多少个。

var inputs = document.getElementsByTagName('input');
if(inputs.length){
  // there's inputs on the page
} else {
  // n
}

  

我想知道有多少输入标签可用..带有

如果您想获取具有给定ID 的输入,请使用getElementById。请注意,ID应该是唯一的(始终是一个且只有一个),并且没有两个元素应具有相同的ID。

var inputWithGivenId = document.getElementById('the-id');
if(inputWithGivenId){
  // `inputWithGivenId` refers to the element with `id="the-id"`
} else {
  // no element of given id
}

  

我是否可以通过id确定输入框是否可用。

嗯,ID应该是唯一的。但是,如果您正在考虑一组<input>您希望定位的<input>,而不是所有class,请考虑改为使用getElementsByClassName

要从DOM中获取具有给定类名的元素,请使用getElementsByClassNamelength返回一个类似数组的结构(NodeList?)并且有一个var elementsWithClassName = document.getElementsByClassName('the-class'); if(elementsWithClassName.length){ // there's elements on the page with the given class // You may want to check if they're <input>. Any element could use the class } else { // there's elements on the page with the given class } 属性来知道检索了多少个。

{{1}}