What is the best way to alter the color of a line that begins with certain characters using javascript/css?

My Python (Flask) application sends data to a Jinja2 template, which then renders it as HTML. Here's an example of the data:

--- a
+++ b
[
@@ -0 +0 @@
 {
  u'po': u'04312',
  u'storage': [
  @@ -2,1 +2,1 @@
  @@ -2,1 +2 @@
  +{u'type': u'FusionIO', u'capacity': 3000, u'number': 2, u'speed': u'N/A', u'total_capacity': 6000},
  ],
  u'serial': u'YYZ666',
  u'added_by': ObjectId('5208f7e054d79f70f9e13f7f'),
  u'edited_by': ObjectId('5208f7e054d79f70f9e13f7f'),
 -u'revision': 2,
 +u'revision': 3,
  u'status': u'Prod',
 -u'edited_date': datetime.datetime(2013, 8, 19, 21, 40, 30, 275000),
 +u'edited_date': datetime.datetime(2013, 8, 20, 13, 34, 25, 621000),
 -u'memory': u'256',
 +u'memory': u'1024',
  u'racked': u'Yes',
 @@  @@
 },
]

This data in HTML format looks like this:

<div class="server-diff">
  <h2 class="dashboard-heading">Diff</h2>
  <p>--- a
+++ b
[
@@ -0 +0 @@
 {
  u&#39;po&#39;: u&#39;04312&##39;,
  u&#39;storage&#39;: [
  @@ -2,1 +2,1 @@
  @@ -2,1 +2 @@
  +{u&#39;type&#39;: u&#39;FusionIO&#39;, u&#39;capacity&#39;: 3000, u&#39;number&#&nbs…
  ],
  u&#39;serial&#39;: u&#39;YYZ666&#39;,
  u&#39;added_by&#39;: ObjectId(&#39;52...      
  </p>

I want to change the text color of lines that start with + to green and - to red. Can JavaScript or jQuery help achieve this using CSS?

If you have any insights on how to implement this feature, I would greatly appreciate your help.

Answer №1

Retrieve the content from the paragraph, break it down into lines, and analyze the first character before applying a specific class to each line:

$('.server-diff p').text(function(_,txt) {
    var lines = txt.split('\n');

    $.each(lines, function(i, line) {
        var start = line.charAt(0);
        if (start == '+') {
            lines[i] = '<span class="green">'+line+'</span>';
        } else if (start == '-') {
            lines[i] = '<span class="red">'+line+'</span>';
        }
    });
    return lines.join('\n');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Ion-button seems to be malfunctioning

I am interested in using special buttons for my ionic 1 project, specifically the ion-button feature outlined on this page: Ionic Buttons. I attempted to create a Round Button and an Outline + Round Button: <h2 class="sub-header" style="color:#4 ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

When it comes to React, an unspoken truth is that undefined could potentially cause issues

I have been attempting to iterate through an array of data, following a guide without much success. The structure of the data file is as follows: import React, {Component} from 'react'; export default [ { id: 1, lk:593458, ld:18033, status: &ap ...

The ng-repeat directive fails to update data from the model

Can anyone help me figure out why my ng-repeat isn't updating with the data from the array I'm trying to display? Here's a snippet of the HTML code: <div ng-controller="photoCtrl as c"> <div ng-repeat="p in c.photos"> ...

Align the second object at the center of a row containing three items

I am trying to align a row of three elements in a specific way. The first element should be floated left, the third element floated right, and I need the second element to float centrally between them. However, all three elements will have dynamic widths s ...

Detect if HTML elements are overlapping in CSS/JavaScript by checking for hover states

My journey into writing HTML/CSS/JS began just a few months ago. I challenged myself to create a 2D game from scratch without using any libraries like jQuery. Here is a snippet of what I came up with: document.addEventListener("keydown",keyDown); funct ...

Click setting disables button's default behavior

Looking for a solution with my form setup: <form> <RaisedButton label={'next'} onClick={this.handleNext} type={'submit'} style={{marginRight: 12}}/> </form> I've noticed that ...

Eliminate spaces within a string using JavaScript

In my quest for knowledge about trimming strings in JavaScript, I came across this intriguing discussion with a regex-based solution. After learning from the thread, I was under the assumption that trim would eliminate the space between "Hello" and "World ...

Problem with the functionality of the "toggled" attribute in redux-form-material-ui

Currently, I am attempting to implement Toggle functionality from redux-form-material-ui: import { Toggle } from 'redux-form-material-ui' When the toggle value changes, it successfully updates in the store upon onChange: <Col xs='3&apo ...

Passing the output of a nested function back to its containing function in JavaScript within Dynamics CRM

Is it possible for the code below to send the boolean value from the inner function back to the parent function displayButton()? This parent function is triggered when a button in Dynamics CRM is clicked. The expected behavior is for the function to retu ...

Using Bootstrap 4 to create a light color overlay on top of an image for enhanced text visibility and emphasis

Trying to apply a light color on top of an image or its parent div to ensure that the text remains visible regardless of the image's darkness. Using the Bootstrap card class for overlaying text over the image but facing issues with opacity dimming bot ...

What is the best way to remove an item from an array inside another object in JavaScript?

I am currently developing an application using Node, mongoose, and express. My goal is to remove an object from an array that is nested inside another object. Here is the structure of the objects: const oldSection = { _id: '62d3f1d221aa21a03fe3bc21& ...

Searching for elements in Selenium using JavaScript's equivalent of findElement(by.className)

I need to locate an id tag within a class tag on an html page. driver.find_element(By.XPATH, "//div[@class='Content warning']/p").get_attribute("id") https://i.stack.imgur.com/NlU8t.png I successfully accomplished this with ...

What is the proper way to invoke an instance method through an inherited method using its name and ensuring the arguments are correctly typed?

We have created a foundational class that will be extended numerous times. Our goal is to implement an `exec` method on this base class, which will take the name and arguments of a method from a derived class and execute it. However, we are encountering a ...

Organizing and Analyzing data in a ng-repeat with AngularJS, influenced by a higher level ng-repeat

Currently tackling the challenge of creating a fairly intricate ng-repeat that involves filtering and parsing. My initial step is to employ ng-repeat to populate a table with 12 months starting from the current month. Following that, I am organizing two ...

Passing JSON data to an ASP.NET action method results in null data being received on the server

Upon examining the JSON data passed via jQuery AJAX to the controller action, I noticed that all values in the Section were null. However, upon inspecting the JSON, I found that there were indeed values present. The following is my JavaScript code where I ...

What could be causing my dropdown links to malfunction on the desktop version?

I've been developing a responsive website and encountering an issue. In desktop view, the icon on the far right (known as "dropdown-btn") is supposed to activate a dropdown menu with contact links. However, for some unknown reason, the links are not f ...

The presence of an additional bracket is being triggered by the JSON array following

Currently, I am developing a function in Freemarker to iterate through all selected checkboxes and then display the same response on the form itself. The form is structured in Freemarker format, and I am utilizing JavaScript to create separate arrays for e ...

"Troubleshooting a dropdown navigation bar problem in CSS

I am currently working on creating a CSS navbar dropdown, but I am encountering some issues. I am not very experienced with CSS, so any assistance would be greatly appreciated. The text within the "Products" box is not changing color like it should, and yo ...

Positioning two buttons side by side in separate columns on the same horizontal alignment

My objective is to arrange these two buttons horizontally on the same level with the help of bootstrap. <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href ...