Ways to alter the CSS class of individual labels depending on the content of textContent

In my HTML template, I'm using jinja tags to dynamically create labels from a JSON object. The loop responsible for generating this content is detailed below.

<div class="card mb-0">
    {% for turn in response %}
        <div class="card-header collapsed" data-toggle="collapse" data-target="#collapse{{turn['turn_id']}}" href="#">
            <a class="card-title"> {{turn['author_name']}} {{turn['date_time']}} </a>
            </div>
                  <div id="collapse{{turn['turn_id']}}" class="card-body collapse in" >
                       <ul>
                            {% for sent in turn['list_of_sentences'] %}
                                <li>{{sent['text']}}</li>
                                {% for tag in sent['tags'] %}
                                    <label><span class="badge" id="{{tag}}">{{ tag }}</span></label>
                                {% endfor %}
                            {% endfor %}
                       </ul>
                  </div>
    {% endfor %}
</div>

A JavaScript function I've written changes the CSS class based on the label's ID by assigning the label's textContent to the ID.

$(window).on('load', change_label_css );

function change_label_css(){
    console.log("Changing CSS classes");
    
    // Logic to change CSS classes based on label textContent
    // Insert code for updating CSS classes here
    
    console.log("End of changing CSS classes");
}

I've noticed that the current logic might not be ideal, especially with different and similar label IDs. Can anyone suggest a better way to iterate through each label and update the CSS class accordingly?

Answer №1

To simplify the process, you can create an object that stores all label names and their corresponding classes:

const labelClassMap = {
    "OT": "badge badge-warning",
    "RES": "badge badge-success"
    ...
}

Next, go through each of the relevant labels that need class assignment. Check their text content against the map you created earlier to set their class values accordingly.

for(let label of document.querySelectorAll("label" /*You may adjust the selector here*/)){
   label.classList.add(...labelClassMap[label.textContent].split(" "))
}

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

Executing Node.js Function from an External File Dynamically

Is it possible to run a Node function from an external file that may be subject to change? main.js function read_external(){ var external = require('./external.js'); var result = external.result(); console.log(result); } setInterva ...

Sending an image via email using a highly limited HTML interface

I am working on setting up a webpage connected to my company's internal Intranet page that is specifically designed to allow an iPad to take a picture and then email the picture using our webmail application. The current HTML code I have only allows m ...

What is the best way to send a file object to a user for download?

When working within a route: app.get('some-route', async (req, res) => { // ... } I am dealing with a file object called file, which has the following structure: https://i.stack.imgur.com/ByPYR.png My goal is to download this file. Cur ...

Create dynamic and interactive content by embedding text within SVG shapes using the powerful D

How can I write text into an SVG shape created with d3.js and limit it to stay inside the shape similar to this example http://bl.ocks.org/mbostock/4063582? I attempted to use a clipPath following the example provided. However, when inspecting with firebu ...

Skipping is a common issue encountered when utilizing Bootstrap's Affix feature

I'm trying to implement Bootstraps Affix feature in a sticky subnav. <div class="container" data-spy="affix" data-offset-top="417" id="subnav"> I've adjusted the offset to ensure there's no "skip" or "jump" when the subnav sticks. Ho ...

Encountering a TypeScript error when using Redux dispatch action, specifically stating `Property does not exist on type`

In my code, there is a redux-thunk action implemented as follows: import { Action } from "redux"; import { ThunkAction as ReduxThunkAction } from "redux-thunk"; import { IState } from "./store"; type TThunkAction = ReduxThunk ...

Utilize JavaScript to extract and exhibit various SQL records stored within a multidimensional array

How can I use JS, JQuery, PHP, and MySQLi to automatically generate an HTML table within a div on a webpage? The table should display data based on user-input search criteria. For example, the user enters a start date and end date, clicks a button, which t ...

Adjusting the transparency of TabBadge in Ionic 2

I am currently working on a project that involves tabs, and I'm looking to update the style of the badge when the value is 0. Unfortunately, I am unsure how to dynamically change the style of my tabs or adjust the opacity of the badge in the style. M ...

The attempt to generate a .zip file using Node.js with Egg framework was unsuccessful

I developed a Node.js service using Egg framework to send a local .zip file (compressed directory) to the browser, but encountered an issue. Below is the code snippet: Egg.js // Code for zipping files async download() { const ctx = this.ctx; co ...

Dynamic Website Layout Bootstrap 4 [ card designs and Tabs ]

Currently, I am in the process of developing a web application that needs to be responsive across various devices including mobiles, tablets, and PCs. My focus right now is on creating a user profile page that adapts well to different screen sizes. To achi ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

Unable to place within div

Utilizing HTML5 to implement the "DnD" function. There is a button that adds divs. I want to be able to drag items into these newly added divs. Currently, I can only drag into existing divs and not the ones added later. How can I resolve this issue ...

What is the best way to split key and value into separate array objects using JavaScript?

Here's a snippet of code I am working with: let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'} var years = []; let i; for (i= obj;i<=obj;i++) { years.push({ edad_beneficiario : i }) } When I run this code, the output i ...

Leverage React components for efficient code reuse and export modules for

I have Project X, which was built using the command "yarn build" and it generated a main.js file. I am trying to use this main.js file as a dependency for another React project Y. Unfortunately, following the steps from React components and module exports ...

Horizontal Screen Sharing on iPad

Currently, I have a two-column website set up using Wordpress. However, I am facing an issue with the right side column scrolling over on iPads. While the page behaves properly on desktops, on iOS devices, the div is able to scroll over the navigation ba ...

Utilize Next.js with Axios for making an HTTP request to a Laravel Lumen endpoint, then showcase the retrieved data within the Next.js

I currently have a Next.js application that utilizes Axios to make calls to Lumen endpoints. The Axios HTTP client functions are organized in a separate folder named services/index.tsx, with sample code as follows: export const register = async (payload: a ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

What is the best way to incorporate autoplay video within the viewport?

My objective is for the video to automatically start playing when it enters the viewport, even if the play button is not clicked. It should also pause automatically when it leaves the viewport, without the need to click the pause button. <script src=& ...

Is there a way to make two parallelograms overlap seamlessly and adjust in size automatically using HTML?

Recently delving into the world of HTML and CSS, I've set my sights on designing something unique involving parallelograms that adjust dynamically. My vision includes four overlapping parallelograms starting from the top at 25%, 50%, 75%, and finally ...

Attempting to align a banner image in the middle using CSS styling

I'm having some trouble getting the banner image to be centered on all screen sizes. It looks good on smaller screens, but on larger ones it seems to be shifting to the left. Here's what I've attempted so far: .banner { padding-top: ...