Search code examples
javascriptcookieshtml-tabletoggleclass

JS: Comparing content in table-cells with cookie data and changing CSS class when success


I have a pre-rendered static website, in which I want to highlight a name in a table-cell. The name is written into a cookie on the system of the user OR in a session on the server. This name has to be compared with all names in the table-cells listed. The table-cell with the matching name has then to be switched to the given class for highlighting. I guess this has to be made with JS. I don't know much JS unfortunately.

If it helps, I can print out some JS code into every single table-cell when pre-rendering the website. Maybe this is useful when changing the CSS class?


Example:

The cookie says that it is "Claus".


Original Table:

<table>
 <tr><td class="tdback">Arnie</td></tr>
 <tr><td class="tdback">Mary</td></tr>
 <tr><td class="tdback">Claus</td></tr>
 <tr><td class="tdback">Donald</td></tr>
</table>

Final Table:

<table>
 <tr><td class="tdback">Arnie</td></tr>
 <tr><td class="tdback">Mary</td></tr>
 <tr><td class="tdactive">Claus</td></tr>
 <tr><td class="tdback">Donald</td></tr>
</table>

Solution

  • To use javascript to get cookies you can reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

    Well hopefully the table has an id, if not you can still get the element another way, but for this example i'll get it using an id:

    var cookie = "yourInnerHtml";
    var list = document.getElementById("yourTable").getElementsByTagName("td");
    
    for (var n = 0; n < list.length; n++) {
        if (list[n].innerHTML == cookie) {
            list[n].className = "tdactive";
        }
    }
    

    This should work with the given example. It first gets all the "td" element's in the table, then for each of them checks if the .innerHTML is the same as your cookie. If it is, it changes that elements class.

    UPDATE:

    I removed the unnecessary return statements and now it should work, as well as highlight all occurrences.