【问题标题】:Get certain attribute of HTMLCollection获取 HTMLCollection 的某个属性
【发布时间】:2021-08-25 12:47:37
【问题描述】:

所以我想知道是否有办法获得例如HTMLCollection 的所有value。所以是这样的:

var users = document.getElementsByName('users')
var userLength = []
for (var i = 0; i < users.length; i++) {
    userLength.push(users[i].value);
}
userLength.sort(function(a, b){return b - a});
console.log(userLength);

...但在一行中,更像这样:

document.getElementsByName('users').value

如果你想运行它,它是为stackexchange 上的sites 部分编写的。不,第二个不起作用。

我不能使用 jQuery,所以this 不适合我。

【问题讨论】:

  • 您的示例不使用innerText 它使用value。从那里开始。也许如果您在问题中添加minimal reproducible example,我们可以帮助调试。
  • 我猜map这里应该够用了
  • 当然你可以在一行中完成....删除返回。 :) 没有什么可以像您想要的那样合二为一。但是 map() 是要走的路。 document.querySelectorAll("[name='users']").map(x =&gt; x.value)

标签: javascript html htmlcollection


【解决方案1】:

首先使用Spread syntax (...)获取元素数组,然后使用Array.prototype.map()获取所有值。最后在返回的结果上链接 sort 方法:

var users = document.getElementsByName('users')
var userLength = [...users].map(el => +el.value).sort(function(a, b){return b - a});
console.log(userLength);
<input name="users" value="11"/>
<input name="users" value="22"/>

【讨论】:

  • 我知道这不是问题的一部分,但有没有办法让程序像document.getElementsByName();-statement 一样返回文本?
  • @gurkensaas,你的意思是字符串格式的值吗?
  • 如果我现在尝试使用字符串,它会给我 NaN。有没有办法同时获取字符串?
  • @gurkensaas,从 +el.value 中删除 +....i,e: [...users].map(el =&gt; el.value).sort(function(a, b){return b - a});
猜你喜欢
  • 1970-01-01
  • 2021-12-04
  • 2016-08-23
  • 1970-01-01
  • 2013-07-06
  • 2019-11-23
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多