Convert table contents to CSS or jQuery

I have an html table similar to this:

<table>
  <tr>
    <td>1</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>1</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>1</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Some text...</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Some text...</td>
  </tr>
</table>

The cells in the first column contain a numerical value of 1, 2, or 3.

Im looking for a neat way to convert this value to something more “graphical” using a client-side approach like CSS (preferably) or jQuery. For example, instead of “1,” the contents of the cell should appear as an icon or dot with a red color. Just setting the background color will also be fine.

UPDATE:

Thanks for all the suggestions. It seems that it was just the Every method from jQuery, which I was missing. :)

Here is my last code. I wrapped it in a separate function, which is called on the finished document even after updating the table.

function fnTransformIcons() 
{ 
  var color;

  $("td.Icon").each(function() { 
  var value = $(this).html();

  switch (parseInt(value))
  { 
    case 0 : color = 'white'; break;
    case 1 : color = 'red'; break; 
    case 2 : color = 'green'; break; 
    case 3 : color = 'yellow'; break;
  } 
  $(this).css("backgroundColor", color); 
  });     
}
+3
4
$(document).ready( function() {
    $("tr").each( function() {
        switch ($("td:first",this).text()) {
            case '1': color = 'red'; break;
            case '2': color = 'blue'; break;
            default: color = 'green';
        }
        $($("td:first",this).css("backgroundColor", color);
    });
});

.

+3

jQuery

$("tr td:first").each(function(){
   // do transformations like $(this).html(...)
});
+1

:

$("tr td:first").each( function() {
    $(this).addClass('my_custom_class_'+$(this).text());
});

CSS

.my_custom_class_1 { background: red; }
.my_custom_class_2 { background: green; }
/* etc. */
+1

, , - :


$(function(){
   $('tr').each(function(){
    var cell = $(this).children().first(); //Get first td
    var new_contents = "";
    for (i=0; i <= parseInt(cell.text()); i++) {
      new_contents += '<span class="counter">&deg;</span>'; //or whatever counter character you like
    }
    cell.html(new_contents);
  });
});

This gives you a result that looks like this:

° Some text ...
°° Some text ...
°°° Some text ...
° Some text ...
° Some text ...
°° Some text ...
°°° Some text ...

But, of course, you could style it, change the counter symbol, use the image instead of & deg ;, etc.

+1
source

Source: https://habr.com/ru/post/1731497/


All Articles