I’m trying to get the value of a span attribute (data-red) inside a table cell.
<td class=" u-tL" headers="due-date" aria-labelledby="due-date"><span data-red="255" style="display: block; width: 75px;">19-JAN-2024</span></td>
I’ve tried the code below but it’s giving me the error
"Uncaught TypeError: spn.getAttribute is not a function"
spn = obj.innerHTML;
console.log(spn.getAttribute('data-red'));
2
Answers
The issue you have is that
innerHTML
returns a string, so you can’t callgetAttribute()
on that. What you need is a reference to the Element object containing thespan
itself. One way to do this would be by usingquerySelector()
.Also note the use of
dataset
overgetAttribute()
in the following example.To access value of data-red attribute, you can use getAttribute method as below
It will work for you