1

This is a portion of my table:

index.php

<tr>
    <th>data_uwr</th>
    <td>-1.413\-5.113</td>
    <td>-3.314\-3.650</td>
    <td>-0.001\-0.010</td>
    <td>-1.052\-1.052</td>
    <td>-1.052\-1.052</td>
</tr>

As you can see, each of the cells has 2 numbers separated by a backslash. Can I somehow apply different colors to each of these 2 numbers? For example, in first <td>, -1.413 would be green and -5.113 would be red.

This is what I tried to do but it did not work:

index.js

// This is how I get the row. What this code does is it colors the entire cell - everything in the cells becomes green.
mainTable.rows[rowNumber].cells[numOfRunsToCompute].style.color = 'green';

// Then I tried splitting cell content into an array (of strings), and coloring each string - each number became a string
let test = mainTable.rows[rowNumber].cells[numOfRunsToCompute].firstChild.textContent.split('\\');
test[0].fontcolor('green');

I used this fontcolor() method but it did not work. Since String is not a DOM element, I am not sure how I can color it.

Edit: My question is not duplicate of this. I do not intend to use RegExp mainly because it is very hard to define a pattern in my case. There are thousands of numbers that I cannot predict. The colorization is done based on formulas (which I did not include here for simplicity).

Edit 2:

This is a snippet of code from my function (you may think that some variables are not declared etc., but note that this a cut-out snippet for simplicity purposes):

for (let numOfRunsToCompute = 2; numOfRunsToCompute < runs; numOfRunsToCompute++) {
    let baseline = mainTable.rows[rowNumber].cells[1].firstChild.textContent;
    let newCellValue = mainTable.rows[rowNumber].cells[numOfRunsToCompute].firstChild.textContent;
    let splitBaseline = baseline.split('\\');
    let splitNewCellValue = newCellValue.split('\\');

    for (let i = 0; i < splitBaseline.length; i++) {
        let numBaseline = Math.abs(splitBaseline[i]);
        let numNewCellValue = Math.abs(splitNewCellValue[i]);

        if (numBaseline >= flagNum) {
            let greenCell = numBaseline * greenNum;
            let orangeCell = numBaseline * orangeNum;

            if (numNewCellValue >= 0 && numNewCellValue < greenCell) {
                // For example, this is where I need to apply those colors
                mainTable.rows[rowNumber].cells[numOfRunsToCompute].style.color = 'green';
            } else if (numNewCellValue >= greenCell && numNewCellValue <= orangeCell) {
                mainTable.rows[rowNumber].cells[numOfRunsToCompute].style.color = 'orange';
            } else {
                mainTable.rows[rowNumber].cells[numOfRunsToCompute].style.color = 'red';
            }
        } else {
            let greenCell = numBaseline + greenOrangeWorse;
            let orangeCell = greenCell + greenOrangeWorse;

            if (numNewCellValue >= 0 && numNewCellValue < greenCell) {
                mainTable.rows[rowNumber].cells[numOfRunsToCompute].style.color = 'green';
            } else if (numNewCellValue >= greenCell && numNewCellValue < orangeCell) {
                mainTable.rows[rowNumber].cells[numOfRunsToCompute].style.color = 'orange';
            } else {
                mainTable.rows[rowNumber].cells[numOfRunsToCompute].style.color = 'red';
            }
        }
    }
}

To put it simply: what this code does is basically some pre-formatting and essentially determining which color to give a particular cell. But in this specific case, I need to color a particular piece of information in the cell, not entire cell.

tera_789
  • 489
  • 4
  • 20
  • You could start by modifying the original table *by hand* (that is, not using javascript) to display the colors you want; *then* you could look into how to make that happen via javascript. – Scott Hunter Oct 10 '18 at 23:41
  • Yeah but the thing is that I cannot modify the table by hand. – tera_789 Oct 10 '18 at 23:59
  • What's your goal? You want to make every first number green and every second number red in every `` via Javascript? – P.S. Oct 11 '18 at 00:20
  • No. The actual goal is to colorize a cell based on some formulas (which I did not include here). The question is how do I color specific text inside HTML ``. I wanted to ask it simple. – tera_789 Oct 11 '18 at 00:28
  • 1
    Possible duplicate of [How to color portion of text using css or jquery](https://stackoverflow.com/questions/24625402/how-to-color-portion-of-text-using-css-or-jquery) – Heretic Monkey Oct 11 '18 at 00:29
  • @HereticMonkey read my edit and edited question title – tera_789 Oct 11 '18 at 00:48
  • Take your pick; there are a few dozen questions out there: [JavaScript: How to change color to only part of the string in an input field?](https://stackoverflow.com/q/45233743/215552), [How to change color for mismatch words in HTML using javascript](https://stackoverflow.com/q/45184143/215552), [Change the color of a text in div using jquery contains](https://stackoverflow.com/q/17232820/215552), [HTML: Changing colors of specific words in a string of text](https://stackoverflow.com/q/4622808/215552) – Heretic Monkey Oct 11 '18 at 02:44

3 Answers3

2

As far as I know, you can't style a specific section of text. You'll be forced to manipulate the DOM, since you said you don't have access to change the source HTML. Try this:

var color1 = 'green'; // or '#008000'
var color2 = 'red';   // or '#ff0000'
var tds = document.getElementsByTagName('td');
for (i = 0; i < tds.length; i++) {
    var td = tds[i];
    var numbers = td.innerHTML.split('\\');
    td.innerHTML = `
        <span style="color:` + color1 + `">` + numbers[0] + `</span> 
        \\
        <span style="color:` + color2 + `">` + numbers[1] + `</span>
    `;
};

This code iterates through your td elements and parses out each number that is already in the cell, then inserts span elements in place of each number, with the span's being colored using CSS.

Of course, if you have more td elements on the page besides the ones you need to manipulate, you'll need to be more specific with the selector.

jtate
  • 2,612
  • 7
  • 25
  • 35
  • I guess this answer assumes that I will insert data into ``, correct? The data is already there. I just need to color it. – tera_789 Oct 11 '18 at 00:51
  • yes, it assumes the data will already be there. this code just manipulates what is already there. edited the answer for more clarification. – jtate Oct 11 '18 at 00:55
  • Oh yeah, I see, I missed it. The thing is that colors are defined dynamically as well (I did not include it in my question for simplicity). Anyway, I will try to incorporate your answer and reply here if it worked out. – tera_789 Oct 11 '18 at 00:59
  • dynamic colors shouldn't be too hard to incorporate, I added a simple addition to my answer that would get you started – jtate Oct 11 '18 at 01:02
  • Take a look at my Edit #2. I added a snippet of code. I am currently coloring the entire cell as you can see. My head is literally exploding right now, I will work on it tomorrow, but if you can incorporate your code into what I posted - it would be appreciated. – tera_789 Oct 11 '18 at 02:01
1

I think this is an awesome question.

The idea is to split the string by backslash and then wrap it with specific tag (contain a style).

Here is the example:

$('table td').each(function() {
  var str = $(this).html();
  var arr = str.split("\\");
  var el1 = '<span class="green">' + arr[0] + '</span>';
  var el2 = '<span class="red">' + arr[1] + '</span>';
  // Replace current column
  $(this).html(el1 + '\\' + el2);
});

And you can write a simple CSS style:

.green {
  color: green;
}
.red {
  color: red;
}

For the example result, just go here https://jsfiddle.net/ngekoding/Lmjpx014/10/

Hope this can help.

Nur Muhammad
  • 174
  • 10
0

You could try nested for loops, to hit each cell, and replace the text with added span tags that can color the text separately. I made sure this works and it definitely works for me:

<!--This Is The Demo Table, Fake Values and different slashes were used to display different results -->
<table>
    <tr>
        <td>red/blue</td>
        <td>blue\green</td>
    </tr>
    <tr>
        <td>hello\pink</td>
        <td>bad\\yellow</td>
        <td>hello\bye</td>
    </tr>
</table>
<!--The Actual JS Starts Here-->
<script type="text/javascript">
    //GLOBAL VARS
    //This one represents all TR Tags in the document
    var tr = document.getElementsByTagName("tr");
    //For all TR Tags, do...
    for (var i = 0; i < tr.length; i++) {
        //Create a Variable, representing all TD Tags inside current TR tag being scanned
        var nestedTD = tr[i].getElementsByTagName("td");
        //For All TD Tags Inside Current TR Tag, do...
        for (var j = 0; j < nestedTD.length; j++) {
            //If The InnerHTML Of Each Tag Contains the "\" Character...
            if (nestedTD[j].innerHTML.includes("\\")) {
                //Then Split The InnerHTML Value Based on "\" (It returns array with ["text", "", "text"])
                var splitContentList = nestedTD[j].innerHTML.split("\\");
                //Replace the InnerHTML with a green and a red span tag, wrapping the texts
                nestedTD[j].innerHTML = "<span style='color: green;'>" + String(splitContentList[0]) + "</span>" + "\\" + "<span style='color: red;'>" + String(splitContentList[2]) + "</span>";
            }
        }
    }
</script>

This code took me a lot of effort, please don't hate on its conventions!! I really hope this helps!

Da Mahdi03
  • 1,468
  • 1
  • 9
  • 18