What would be the best method for refreshing CSS following the dynamic addition of data using jQuery for optimal efficiency?

This paragraph was inserted following an ajax request:

<tr id="product1" class = "success">
    <td>1</td>
    <td>product one</td>
</tr>

The success class gives the row a green background, but this style is not applied since the row was added dynamically.

I have seen solutions involving dynamic loading of CSS, but I am curious about the most efficient approach, especially when dealing with a large stylesheet.

I am using Bootstrap:

        <table id = "table_result" class="table">
          <thead id ="table_result_search">
            <tr>
              <th>#</th>
              <th>Product</th>
              <th>Price</th>
              <th>Stock</th>
            </tr>
          </thead>
          <tbody>

          </tbody>
        </table>

and jQuery:

//ajax
var tr = TrTableResult(id,nome, stock, price, n);
$("#table_result_search").append(tr);
//end of ajax
function TrTableResult(id,nome,stock,price,n){
var color = new Array("success", "error", "warning", "info");
var tr = '<tr id ="'+id+'" class="' + color[n] + '">';  
  tr+= '<td>'+ id +'</td>';
  tr+= '<td>'+ product+'</td>';
  tr+= '<td>'+ price +'</td>'; 
  tr+= '<td>'+ stock +'</td>'; 
  tr+= '</tr>';
  return tr;
}

Answer №1

Revised response:

After reviewing your quoted markup and code, it is evident that the table class is present, indicating that the initial answer provided below is not the issue.

However, it is important to note that you are appending your tr to the thead element:

$("#table_result_search").append(tr);

Meanwhile, your markup states:

<thead id ="table_result_search">

The reason you are not observing the effects of the success class is because of the following CSS rule:

.table tbody tr.success > td {
  background-color: #dff0d8;
}

Please take note of the tbody in the selector. Consequently, the selector does not match as you are appending the row to a thead, not a tbody.


Initial response:

As pointed out by several individuals in the comments, CSS applies to all elements that match the respective selectors, whether dynamically added or not.

If you are experiencing issues with the success class not functioning, it is likely due to the absence of the table class on your table element.

The CSS rule from bootstrap is as follows:

.table tbody tr.success > td {
  background-color: #dff0d8;
}

It is important to acknowledge that the rule begins with a class selector (.table), not a tag selector (table).

For example, the following markup will not apply those styles to the td in the table:

<table>
  <tbody>
    <tr id="product1" class="success">
      <td>1</td>
      <td>product one</td>
    </tr>
  </tbody>
</table>

Live Example | Source

However, by simply adding the table class to the table tag, like in the following markup:

<table class="table">
  <tbody>
    <tr id="product1" class="success">
      <td>1</td>
      <td>product one</td>
    </tr>
  </tbody>
</table>

Live Example | Source

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

Encountering an issue with React and material-ui-pickers date-io Jalaali Utils: receiving a TypeError stating that utils.getDayText is not recognized as

This issue is different from what was discussed in https://github.com/mui-org/material-ui-pickers/issues/1440 because I am not facing any problems with the original implementation. Referencing the link provided here , I have utilized JalaliUtils from @da ...

Understanding CSS classes in ReactJS Material UI componentsJust wanted to clarify some things

When it comes to styling Material UI components, the recommended approach is to utilize their useStyles function. Here's an example: const useStyles = makeStyles(theme => ({ root: { marginTop: '15px', display: 'f ...

Tips for Achieving Observable Synchronization

I've encountered a coding challenge that has led me to this code snippet: ngOnInit(): void { this.categories = this.categoryService.getCategories(); var example = this.categories.flatMap((categor) => categor.map((categories) = ...

Vue JS ensures that it has all the necessary data before proceeding with the

I've been grappling with a VueJS data rendering issue for a few weeks now. My approach involves making axios calls, some nested within others. The problem I'm facing is that the data renders before the calls have completed, resulting in an empty ...

Issue with state change in Component (React with Redux)

I am another person facing a similar issue. I have been unable to identify the error in my code yet. I suspect it has something to do with mutation, but despite trying almost everything, I am at a loss. My component does not update when I add new items to ...

The steps to display a partial view within another view in React Native

Attempting to show the View after calling alert("Hi") in the renderMoreView function has been challenging for me. The alert works fine, but displaying the View is where I am encountering issues. class Main extends Component { state = { moreButton: f ...

React Native Router Flux encountered duplicate keys in two children

Version(s) react-native-router-flux v3.31.2 react-native v15.2.1 I am encountering an issue when trying to call Actions.dialog() multiple times and receiving an error message. Despite attempting the fix mentioned in https://github.com/aksonov/react-nat ...

Add the item and increase its value within an array using AngularJS

http://plnkr.co/edit/NDTgTaTO1xT7bLS1FALN?p=preview <button ng-click="addRow()">add row</button> <div ng-repeat="row in rows"> <input type="text" placeholder="name"><input type="tel" placeholder="tel"> </div> I am cur ...

Positioning a div at the bottom of a webpage without using absolute positioning in HTML

Check out the fiddle. I've included some CSS to position the tab on the right side. My goal was to have those tabs in the lower right corner of the container. If I use absolute positioning for the div, it messes up the tab content width. I tried ad ...

Utilizing timezones with Moment.js

Currently, I am utilizing momemt.js and moment-timezone.js to present time in the browser. At this time, I have received epoch time from the server which has been converted to central time. My goal now is to exhibit the time in EST/EDT format. To achieve t ...

Forming a space between borders

I'm attempting to create a space within a div's border that can accommodate an image, much like so: Is there a method to achieve this using only CSS? The only solution I have found is: .box { background: url(img.png) bottom left; border ...

What is the process for uploading an image encoded in base64 through .ajax?

I am currently working with JavaScript code that successfully uploads an image to a server using an AJAX call. Here is the ajax call snippet that is functioning properly. $.ajax({ url: 'https://api.projectoxford.ai/vision/v1/analyses?', ...

You have encountered an error: Uncaught TypeError - the function (intermediate value).findOne is not defined

Encountering an error when attempting to call the getStocks function from a Vue component. smileCalc: import User from "../models/user.js"; let userID = "62e6d96a51186be0ad2864f9"; let userStocks; async function getUserStocks() { ...

The SecurityError known as DOM Exception 18 can be triggered when attempting to use Backbone fetch with a datatype of "xml"

Encountering an error while attempting to fetch an "xml" response using backbone. My fetch code: itenary.fetch({ data :{date:dayFormatToSend.toString(), advisorId:"0000222186"}, dataType:"xml", success:function(response){ console.log(response); } ...

Tips for selecting the initial and final elements of a specific class

Here is a simple example of table markup: <div class="table"> <div class="table__headers"></div> <div class="table__row"></div> <div class="table__row"></div> </div& ...

IE may not support the use of XMLHttpRequest with the POST method

When interacting with a server through an XMLHttpRequest to post data, the code typically follows this structure: var xhr = new XMLHttpRequest(); var url = 'http://myurl/post'; xhr.open("POST", url, true); xhr.setRequestHeader("Content-type", " ...

Errors that occur when parsing templates in Angular 2

I'm encountering a template parse error with my Angular 2 component using the following template: <div *ngIf="chapter == 1"> <p><h4><br><b>Exercise</b>: Get the Groceries starting point<br></h4 ...

Searching for an element with a changing name using jQuery - Struggling with quotes

Looking to navigate my DOM based on the value of an option in a select box. The value of "searchkey" can vary based on user input, for example: searchkey = dell'anno searcheky = dell"anno These options, particularly the first one, can cause issues ...

What's the point of repeatedly confirming prompts?

I am using Jquery ajax call to delete data from my HTML table. Everything works fine, but the alert message keeps showing repeatedly. What could I be doing wrong? Delete button "<a href='#my_modal' class='delete-Record'>Del ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...