【问题标题】:Select an element without ID in JavaScript [duplicate]在JavaScript中选择没有ID的元素[重复]
【发布时间】:2016-02-06 21:20:28
【问题描述】:

我在更改 textbot 的值时遇到了一点问题。问题是textbox没有分配id,所以getElementById不起作用,getElementsByName也不起作用。

<input type="text" class="textbox" name="custom_reason" size="50" maxlength="120" value="">

我将如何改变它的价值?

谢谢。

【问题讨论】:

  • 还有其他DOM方法可以获取getElementsByClassName/querySelector等元素
  • 你能用jQuery吗?
  • .getElementsByName("custom_reason") 返回一个您需要索引才能访问的数组。

标签: javascript html


【解决方案1】:

您可以改用该名称:

var x = document.getElementsByName("custom_reason")[0];

【讨论】:

    【解决方案2】:

    一种选择是使用querySelector 并使用attribute selectors 包含所有元素的功能:

    document.querySelector('input.textbox' +
                           '[type="text"][name="custom_reason"]' +
                           '[size="50"][maxlength="120"]' +
                           '[value=""]').value = 'foo';
    &lt;input type="text" class="textbox" name="custom_reason" size="50" maxlength="120" value=""&gt;

    如果name 是唯一的,您可能需要使用getElementsByName (Fiddle):

    document.getElementsByName('custom_reason')[0].value = 'foo';
    

    注意还有更多,比如迭代所有输入或使用 jQuery。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 2013-03-15
      相关资源
      最近更新 更多