Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working on a reporting application that pulls info from different servers and displays them in a specific format. I am also making this completely responsive so the tables that I get look something like this:

<table>
  <tr>
    <td width="30%">Date</td>
    <td width="40%">Description</td>
    <td width="17%">Result</td>
    <td width="15%">Range</td>
    <td width="8%">Comments</td>
  </tr>
</table>

I want to know how I could add data-label to each depending on what width they have.

like

<td width="30%" data-label="Date">Date</td>

I don't actually need the date field so I have hidden that entire field with CSS its just the description, result, range and comments.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

Pulling a list of all td elements in the document, and applying the appropriate labels when the widths-in-question are seen:

var tds = document.getElementsByTagName('td');

for ( var i = 0; i < tds.length; ++i )
  {
    var td = tds[i];
    var label = null;
    
    switch (td.getAttribute('width'))
    {
      case '30%':
        label = 'Date';
        break;
      case '40%':
        label = 'Description';
        break;
      case '17%':
        label = 'Result';
        break;
      case '15%':
        label = 'Range';
        break;
      case '8%':
        label = 'Comments';
        break;
    }
    
    if (label)
      {
        td.setAttribute('data-label', label);
      }
  }
td[data-label=Date] {
  color: red;
}

td[data-label=Description] {
  color: green;
}

td[data-label=Result] {
  color: purple;
}

td[data-label=Range] {
  color: blue;
}

td[data-label=Comments] {
  font-style: italic;
}
<table>
  <tr>
    <td width="30%">Date</td>
    <td width="40%">Description</td>
    <td width="17%">Result</td>
    <td width="15%">Range</td>
    <td width="8%">Comments</td>
  </tr>
  <tr>
    <td width="30%">Blah</td>
    <td width="40%">Blah</td>
    <td width="17%">Blah</td>
    <td width="15%">Blah</td>
    <td width="8%">Blah</td>
  </tr>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...