如何在JS中使用forEach迭代元素时获取元素的名称?

时间:2016-10-29 21:29:52

标签: javascript foreach

我使用tdforEach迭代多个document.querySelectorAll元素。如何在此循环中访问元素的name值?

这就是我现在正在尝试的,而且它还没有被定义。

HTML:

<td name="monday" class="from">foobar</td>
<td name="tuesday" class="from">foobar</td>
<td name="wednesday" class="from">foobar</td>
<td name="thursday" class="from">foobar</td>
<td name="friday" class="from">foobar</td>
<td name="saturday" class="from">foobar</td>
<td name="sunday" class="from">foobar</td>

JS:

const myNodeList =  document.querySelectorAll('.from'); // grabs some td elements
[].forEach.call(myNodeList, function (item) {
    console.log(item.name);
});

结果:

undefined
undefined
undefined
undefined
undefined
undefined
undefined

1 个答案:

答案 0 :(得分:3)

更改

console.log(item.name);

到:

console.log(item.getAttribute("name"))