javascriptattributesgetattribute

How to get the attribute of an innerHTML?


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

Solution

  • The issue you have is that innerHTML returns a string, so you can't call getAttribute() on that. What you need is a reference to the Element object containing the span itself. One way to do this would be by using querySelector().

    Also note the use of dataset over getAttribute() in the following example.

    // your existing reference to the 'td'
    const obj = document.querySelector('.u-tL');
    
    // get a reference to the child 'span'
    const span = obj.querySelector('span');
    
    // get the data attribute:
    const data = span.dataset.red;
    console.log(data);
    <table>
    <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>
    </table>