Is there a way to alter the appearance of an HTML element without an ID using a JavaScript function?

I have a specific goal in mind, but I'm struggling to articulate it concisely. Despite conducting extensive research, none of the suggested solutions seem applicable in my case.

Objective: I aim to change the background color of a div based on the dance style using a JavaScript function. When the page loads, the background color of the dance style should be set accordingly.

My Razor Page iterates through and displays various dance events (other columns are omitted for clarity).

@foreach (var item in Model.Dances)
{  
<tr>
    <td>
        <div> @Html.DisplayFor(modelItem => item.DanceStyle) </div>
    </td> 
</tr>
}

Due to the dynamic nature of the rows, the div elements do not have unique IDs. Therefore, calling a JavaScript function with the Dance's style parameter and using getElementByID to change the background color of the DIV is not feasible.

Below is an initial attempt at a potential solution:

<div onload="fColorDIV(this.value)"> DanceStyle </div>

function fColorDIV(this)
{
        switch(this)
        {
            case "Waltz":
                dancestyleBGcolor = "PapayaWhip"
                break;
            case "WCS":
                dancestyleBGcolor = "LightSalmon"
                break;
            case "Zydeco/Cajun":
                dancestyleBGcolor = "Yellow"
                break;

            default:
                dancestyleBGcolor = "LightGray"
         } 
    return dancestyleBGcolor;

}

I am unsure if the onload event will work correctly when the DIV is being rendered on the page. Additionally, assigning an ID to the element is not viable since all rows would end up having the same ID for their DIVs.

Answer №1

@CodeThing provided valuable assistance by directing me to a helpful resource on dynamically adding classes to HTML elements using razor syntax at this link.

Based on the example utilizing the class attribute, I assumed that the same approach would apply for styles and other HTML attributes, which turned out to be correct.

I managed to implement it successfully for the style attribute by invoking a function within the class (thanks to @Temu) and setting various attributes such as border radius and text alignment.

<div style="background-color:@DaBamba.Helpers.NextEvent.AddStyleColor(item.DanceStyle);border-radius:10px;text-align:center;"> @Html.DisplayFor(modelItem => item.DanceStyle)</div>

Below is the function that I invoke within a class:

 public static string AddStyleColor(string thisStyle)
        {
            string dancestyleBGcolor = "";
            switch (thisStyle)
            {
                // List of cases with corresponding color values
            }


            return dancestyleBGcolor;
        }

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

Special Table Spacing

Within my table, I am looking to create spacing between cells without setting padding and/or margin on each individual td. While using the CellSpacing and/or CellPadding properties of the table could be a potential solution, these properties apply space on ...

Opening the Instagram app in Instagram's built-in browser

<a href="instagram://user?username=someuser">Open Instagram</a> Works fine on Google Chrome on my Android phone. However, it does not work from Instagram's in-app browser. I keep getting a 'Page can't be loaded' error messa ...

Expanding properties in a React component based on certain conditions using TypeScript

I am attempting to dynamically expand my component props based on whether a specific prop is included. The goal is to add attributes from an anchor if the href prop is provided, and include attributes from a button if it is not. Is this achievable? Chec ...

Helping individuals identify the HTML5 Geolocation notification

Currently working on a website that requires users to accept the browser prompt for location sharing. Many users seem to overlook this prompt, which can lead to issues. The main problem we are facing is that each browser displays this prompt differently: ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

Retrieving the checkbox's status from the database

I have implemented a basic checkbox that updates its state in the database when clicked or unclicked. Is there a way to retain this state and have it displayed as checked if the page is refreshed? Essentially, I want the checkbox to remember its last state ...

The async/await feature is not pausing for the completion of the async.map function call

I'm encountering an issue in my Node.js app where I need to gather and format data using a helper function for an API endpoint. The problem arises when trying to loop through an array and make asynchronous calls to the database for each entry. Despite ...

Calculating the sum in a VueJS pivot table

Currently, I am delving into VueJS and working on migrating a basic application from Laravel with the blade template engine. The backend remains unchanged, consisting of a straightforward RESTful API with 3 tables: Books, Places, and a pivot table named B ...

Is it possible for Angular.js to interact with JSTL expression language?

Is it possible for angular.js to interact with JSTL expression language? I am trying to generate ng-options using an array. Here is an example of what I am attempting to accomplish: <select ng-model="detail" ng-init="Categories = '${Categories}& ...

What is the most effective way to send a list of objects to a Controller

https://i.stack.imgur.com/oyi5v.png This form is for billing purposes. You can add the item name, quantity, and price multiple times to calculate the total amount. Once you click on submit, all the included items along with other parameters like bill nu ...

What's the most effective method for identifying a pattern within a string of text?

For the sake of honing my skills, I undertook a practice task to identify patterns of varying lengths within a specified string. How can this function be enhanced? What potential issues should I address in terms of optimization? function searchPattern(p ...

Do I need to use the "--save" flag in npm to add dependencies to the "package.json" file?

Do I really need to use the "--save" flag in order to add an installed dependency to the "package.json" file? I conducted a test without the "save" flag and found that the package was still added to the "dependencies" section. It seems like it is the defa ...

Animating a spinning SVG path around its center within a larger rectangular box

Is there a way to rotate a smaller SVG path within a larger rectangle around its own center? The current code rotates the entire space. <animateTransform attributeType="xml" attributeName="transform" type="rotat ...

Ensure that the two background images are identical in size and content

Can someone assist me with achieving vertical equality for two background images like in this example image? Currently, I have the following styling applied: background-repeat: no-repeat, repeat-x, repeat-y; background-position: 925px center; However, t ...

Tips for locating all events linked to a specific text box using JQUERY

I'm currently encountering a major issue with textboxes on a page that I've been tasked to update. Whenever I attempt to input text into the textboxes, the span element next to them disappears. My application is built using ASP.NET and relies on ...

Why are my functions still being called asynchronously? I must be missing something

My task involves downloading 5 files exported from our school's database and running a query based on the first export. There will be queries for the other four files, and since there are three schools, my functions need to be scalable. I have two fu ...

An unexpected 'undefined' value is being added to a particular Web API request

I am encountering an issue in my Angular application where the word 'Undefined' is being appended to a specific WebAPI call, causing both registerUser and login requests to fail. Here are the problematic request URLs: Request URL: http://localho ...

Creating an empty array of objects in Vue 3 requires using the Vue 3 syntax

In my project using Vue3 with Nuxt, I encountered an issue. My goal is to initialize an empty array of objects and then populate it. let results = ref([]); results.value = [ { "name": input.value, } ...

Tips for customizing ngTable with expandable detail panels

I am currently working on styling a layout using ng-table, which includes a table within each row. The expanding functionality in Angular is implemented as follows: <tr ng-if="org.expanded" ng-repeat-end> <td></td> <td></td& ...

Building with bricks and mortar does not involve organizing visual content

I'm currently trying to organize some fairly large images using masonry, but the code below doesn't seem to be working. I'm using node.js with express and have installed the masonryjs package in an attempt to make it work, but that approach ...