Ways to apply CSS to a changing div ID

I am looking to apply CSS to a dynamically generated div ID.

var status = var status = item.down().next().innerHtml();
if(status == "test")
{  
    var c = 'item_'+i ;
    c.style.backgroundColor = 'rgb(255, 125, 115)';
    //'item'+ i.style.backgroundColor = 'rgb(255, 125, 115)';
}  

In this case, "item_" + i represents dynamic IDs for each row such as item_1, item_2, item_3, and so on. I want to add CSS to specific rows, like item_1 and item_3 among others.

How can I achieve this?

Answer №1

To properly apply the style property, make sure to retrieve the element by using its id. You can achieve this by utilizing document.getElementById().

var status = var status = item.down().next().innerHtml();
if(status == "test")
{  
    var c = 'item_'+i ;
    document.getElementById(c).style.backgroundColor = 'rgb(255, 125, 115)';
    //'item'+ i.style.backgroundColor = 'rgb(255, 125, 115)';
} 

Alternatively, you can incorporate jQuery's id-selector and use css() for applying CSS styles.

var status = var status = item.down().next().innerHtml();
if(status == "test")
{  
    var c = 'item_'+i ;
    $('#'+c).css('background-color','rgb(255, 125, 115)');
    //'item'+ i.style.backgroundColor = 'rgb(255, 125, 115)';
} 

Answer №2

Utilizing suggestions from fellow users is one way to approach this task. Another method is to employ the following technique. When solely relying on plain JavaScript, it is necessary to first locate the element by utilizing the function document.getElementbyId

var x = document.getElementbyId('item_' + i);
x.style.backgroundColor = 'rgb(255, 125, 115)';

Answer №3

Discover numerous methods to attain the desired outcome. Along with other solutions, you can utilize jQuery for achieving this task.

$("div#" + dynamic_id).css("background-color", "rgb(255, 125, 115)");

Answer №4

If you want to apply CSS to a dynamic div element, you can achieve this by using the following code snippet:

$("div"+dynamic_id).css({"color":"rgb(255, 125, 115)"});

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

Iterate through pictures in the gallery

Using jquery, I have created a custom gallery with fancybox. However, I am facing an issue with achieving infinite looping of images when the user clicks on the next/previous button. Each time the button is clicked, a JavaScript method is called to dynamic ...

How can we assign various class names depending on the value of an object?

I have a set of objects stored in my component. I need to dynamically apply different classes based on the value of the ErrorLevel property within each object. If an object has ErrorLevel equal to 1, I want to assign the following classes to various elemen ...

Using Angular JS version 1.2.26 to implement promises within a forEach iteration

I am working on a JavaScript project where I have implemented an angular.forEach loop to iterate over image configuration objects and create Image() objects using the URLs from the config. My goal is to ensure that none of the resulting images are returne ...

Displaying HTML elements conditionally in React depending on boolean values

Developing a component that limits the display of text to the first 40 characters, but can show the full description when a Chevron click event is triggered. The goal is to have the content expand in a similar fashion as it currently does with the Accord ...

Unexpected character appearing in Android 2.3, whether using the li or ul tag

Having an issue with my social icons on the top of my website displaying unwanted symbols in Android 2.3. Can't figure out the cause even after ruling out <a> tags and associated CSS. Any thoughts on what the problem might be? I've remove ...

Utilize a CSS style or class on a div element

Looking for a way to style alternate div elements within a parent div? Check out this example: <div id="comment"> <div id="m1">...</div> <div id="m2">...</div> </div> I tried to use some jQuery to add a CSS c ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Extracting necessary data from a JSON file and generating a new JSON file with the selected information

My task involves parsing a JSON file to extract events that fall within a specified start and end time provided via an HTTP GET request. The goal is to return these filtered events as a new JSON-encoded response. Despite brainstorming two potential solutio ...

Removing a Request with specified parameters in MongoDB using NodeJS

Working with Angular 4 and MongoDB, I encountered an issue while attempting to send a delete request. My goal was to delete multiple items based on their IDs using the following setup: deleteData(id) { return this.http.delete(this.api, id) } In order ...

Using VueJs's createElement() to dynamically insert HTML content

I am currently working on a component that converts all icons to SVG format. By the end of my code, I have included the following: return createElement('i', '<SVG>CODE</SVG>' ) In the spot where the SPA ...

Handling TextChanged Event of a TextBox in ASP.NET using C#

I'm currently designing a POS screen that allows barcode scanning directly into a textbox. I want to implement a code behind procedure that adds the barcode-related data to the grid as soon as the textbox text changes. This is how my textbox looks: &l ...

JQuery WCF Service is returning a 400 Bad Request response

I developed a WCF web service in ASP.NET 4.5 using VS2012 that delivers a JSON response successfully via the built-in webservice client. The endpoints are correctly configured in the Web.config file. However, I encountered an issue on the client side with ...

Understanding the sequence of operations in Javascript using setTimeout()

If I have the following code: function testA { setTimeout('testB()', 1000); doLong(); } function testB { doSomething(); } function doLong() { //takes a few seconds to do something } When I run testA(), what happens after 1000 mill ...

The Jquery ajax call encountered an error due to a SyntaxError when trying to parse the JSON data, specifically finding an unexpected character at

I've developed a web application that utilizes just four scripts for dynamic functionality. Overview: Init.php = Database, index.php = webpage, api.php = fetches data from server/posts data to server, drive.js = retrieves information from api.php a ...

Trouble arises when rendering nested components in React Router 4

My issue lies with implementing React Router 4 while utilizing "nested" routes. The problem arises when one of the top routes renders a component that matches the route, even though I do not want it to be rendered. Let me provide the relevant code snippets ...

What do you want to know about Angular JS $http request?

My goal is to send a request using $http with angular js in order to retrieve a json object from google maps. $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city&a ...

unable to decrease the dimensions of the image within the next/image component

Why won't the image size change? I've attempted to adjust the width and height in the component and also tried styling with className, but no luck. The image only seems to resize when using a regular img tag. Here is my code: function Header() ...

Encountered a TypeError in Angular printjs: Object(...) function not recognized

I'm currently working on integrating the printJS library into an Angular project to print an image in PNG format. To begin, I added the following import statement: import { printJS } from "print-js/dist/print.min.js"; Next, I implemented the pri ...

The submission of the form is not functioning correctly when triggered by JavaScript using a button

My website was designed using a CSS/HTML framework that has been seamlessly integrated into an ASP.NET site. Within a ContentPlaceHolder, I have implemented a basic login form. The unique aspect is that I am utilizing the onclick event of an image to subm ...

A guide on utilizing Puppeteer for capturing screenshots of web pages with embedded videos

Currently, I am using Puppeteer to access a website and capture a screenshot of a video. Unfortunately, the default Chromium browser that Puppeteer uses does not support certain video types. I have managed to get it working by launching Puppeteer with a l ...