skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. To access value of data-red attribute, you can use getAttribute method as below

    const spanElement = obj.querySelector('span');
    let redValue = spanElement.getAttribute('data-red');
    console.log(redValue);
    

    It will work for you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search