Skip to content

How to change color of a cell in HTML table using JSoup?

I need to parse a table using Java and Jsoup and change the color of the cell based on it’s value. This is what the html table looks like and it is how the color of the cell needs to be defined

 <td colspan="1">Test1</td>
 <td colspan="1">JD</td>
 <td colspan="1">N</td>
 <td colspan="1">A</td>
 <td class="highlight-#fff0b3" title="Background color : Light yellow 100%" data-highlight-colour="#fff0b3">COLOR YELLOW</td>
 <td class="highlight-#fff0b3" title="Background color : Light yellow 100%" data-highlight-colour="#fff0b3">YELL</td>
 <td class="highlight-#fff0b3" title="Background color : Light yellow 100%" data-highlight-colour="#fff0b3">N/A</td>
 <td class="highlight-#fff0b3" title="Background color : Light yellow 100%" data-highlight-colour="#fff0b3">N/A</td>

I wrote a script that can ready the value of a cell and change the text from it, however I am unable to also change the color

Document doc = Jsoup.parse(html);
Elements rows = doc.getElementsByTag("tr");
    String status = "Pass"
    for(Element row : rows) {
            String Column1 = row.getElementsByTag("td").get(0).text();
            if(Column1 == "MyValue"){
                if(status == "Pass"){ // Everything below doesn't work
                    row.getElementsByTag("td").get(1).title("Background color : Medium green 65%"); 
                    row.getElementsByTag("td").get(2).title("Background color : Medium green 65%"); 
                    row.getElementsByTag("td").get(3).title("Background color : Medium green 65%"); 
                } else if(status == "Fail"){
                    row.getElementsByTag("td").get(1).title("Background color : Medium red 85%"); 
                    row.getElementsByTag("td").get(2).title("Background color : Medium red 85%"); 
                    row.getElementsByTag("td").get(3).title("Background color : Medium red 85%"); 
                } else{

This is the error I am getting:

No signature of method: org.jsoup.nodes.Element.class() is applicable for argument types: (java.lang.String) values: [highlight-#57d9a3]
10:44:33  Possible solutions: clone(), clone(), addClass(java.lang.String), hasClass(java.lang.String), val(java.lang.String), getClass()



row.getElementsByTag("td").get(1) returns an Element, which doesn’t have a class method.

Though, it has a classNames method, and that accepts a Set<String> as a parameter (even if you just need to pass a single class).

So you can do something like


And so on.

Aside from that compilation error, if(status == "Pass") is not how you compare strings in java. You need to do something like if("Pass".equals(status)).

10 People found this is helpful