f7n f7n - 1 month ago 6
Javascript Question

How to get an element's name when iterating through elements with forEach in JS?

I'm iterating through multiple

td
elements using
forEach
and
document.querySelectorAll
. How can I access an element's
name
value within this loop?

This is what I'm trying at the moment, and it's returning undefined.

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);
});


result:

undefined
undefined
undefined
undefined
undefined
undefined
undefined

O_Z O_Z
Answer

change

console.log(item.name);

to :

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