Skip to content Skip to sidebar Skip to footer

Add Multiple New Attributes By Checking The Existing Ones

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 tha

Solution 1:

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>

Solution 2:

You can try something along these lines:

One thing I'd suggest, though, is to use

<td style="width:30%;">Date</td>

instead of the width attribute. http://www.w3schools.com/tags/att_td_width.asp

The width attribute is not HTML5 compliant.

window.onload = function(){
  var tds = document.querySelectorAll('#mytable td'); 
  
  for(var i = 0; i < tds.length; i++){
    tds[i].setAttribute('data-width', tds[i].getAttribute('width'));
  }
}
<table id="mytable">
  <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>

Solution 3:

$(document).ready(function (){
              $('#mytable tr td').each(function(){

                  console.log($(this).attr("data-width",$(this).text());
              })


          });

plz check it


Post a Comment for "Add Multiple New Attributes By Checking The Existing Ones"