user275615
user275615

Reputation: 71

Change the class of a div to that of a different CSS class using node.js

I have an index.html file that will contain some boxes that will default to green. I want to use node.js to change the colour of those boxes (by changing the div class from "red" to "green") based on a value I plan to get from a rest API (basically a 0 or a 1).

<div id="JIRA" class="small-box bg-green">

I want to be able to read index.html, then change:

class="small-box bg-green">

to

class="small-box bg-red">

Then write the change back to index.html before it is sent off to the user. I would use client side js for this but I can't expose the API token for security reasons.

I've seen cheerio and jsdom for parsing and manipulating the HTML but I've been unable to find an example of how to change the actual class. Is this possible with node.js?

Upvotes: 0

Views: 1681

Answers (2)

user275615
user275615

Reputation: 71

I didn't really give enough information in my initial question but I was able to figure out how to do what I was intending so I thought I'd post what I came across.

Please note, the ONLY reason that this needed to be done server side - and not in client side JS - is because I needed to send API requests to a service requiring API tokens. This service does not offer the ability to give out read-only API tokens, so exposing the master API token in client side Javascript is a large security issue (anyone using developer tools would be able to have full control over the service).

Using express as our node server to serve the static, I added an app.get line to listed for /getStatus: app.get('/getStatus', function (req, res){ .... }); This function would make a request to the API in question, and return a json response.

The rest was done with client side Javascript. $(document).ready(function(){ $.get('http://' + window.location.hostname + ':8080/getStatus', function(status){ $('response').html(status); From the last line there, status will contain the JSON object with the relevant details I needed. Then it was just a matter of using document.getElementById(id).className = "the class name";

Thanks to those who posted comments and answers.

Upvotes: 1

Subomi
Subomi

Reputation: 410

Instead, just use a templating engine, Lookup Pug Templating Engine

Upvotes: 0

Related Questions