CSS :contains selector after adding a script through Ajax append operation

Is there a way to change the text color in

$('td:contains("text")').css('color','red')
after an Ajax load script?

Here is the main code snippet

<div id="datatable"></div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script id="body">$(document).ready(function(){$.ajax({url:"script.js",type:"POST",cache:!1,success:function(c){c&&$("#body").append(c)}})});$('td:contains("text")').css('color','red');alert("script")</script>

Code for script.js

var datatable = document.getElementById("datatable");
var table = "<table><tr><td id='tdone'>Text</td></tr>" + 
      "<tr><td id='tdtwo'>Two</td></tr></table>";
datatable.appendChild(table);

alert("code");

I'm facing an issue with the order of alerts, where the Script alert pops up before the code alert.

Are there any methods or techniques to wait until the Ajax call finishes and the table is appended to the document before firing the script?

I have tried using Success, Complete, Find, and AjaxStop methods but none of them seem to work.

Answer №1

To properly apply this CSS

$("td:contains("text")").css('color','red')
, it needs to be included within the success callback function of an AJAX call instead of executing it outside. For example:

success:function(response){
    $("#content").append(response);
    $("td:contains("text")").css('color','red')
}

Answer №2

To execute code after an Ajax request is completed, simply utilize the success block within the Ajax function.

$(document).ready(function(){
  $.ajax({
    url:"script.js",
    type:"POST",
    cache:false,
    success:function(response){
        response&&$("#content").append(response);
        $("td:contains(\"text\")").css('color','blue');
        alert("script executed successfully");
        //Code placed here will be executed after completion of Ajax
    }
  });
  //This section runs before Ajax completion
});

It's important to escape inner double quotes in your code to avoid conflicts with nested quotes of the same type.

Answer №3

If you're looking to customize the color of a specific td, here's how you can do it:

$.ajax({
    url:"URL ",
    type:"POST",
    success:function(Response){
        $("tr > nth-child(1)").css("color","red");
        //Any additional code here will execute after the Ajax request is completed
    }
  });

If you prefer to assign colors by row, simply give an ID to the row and pass it to the function:

To change the color of a specific td:

$.ajax({
    url:"URL",
    type:"POST",
    success:function(Response){
        $("#id td : nth-child(1)").css("color","red");
        //Any additional code here will run after the Ajax request finishes
    }
  });

This approach should help resolve your issue.

Answer №4

<div id="datatable"></div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="your-custom-path/script.js"></script>
<script id="body">
$(document).ajaxStop({
   $('td:contains("text")').css('color','red');alert("script");
});
</script>

Explore more at : https://api.jquery.com/ajaxStop/

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

Resizing a floated div causes the image to break out

My webpage has a container div with two floated left divs inside, positioned side by side. The right div contains a YouTube video and an image. However, when I resize the page, the video and picture flow out of the containing floated div instead of dropp ...

Dynamic image uploading with Ajax

One issue I've encountered is with the ajax image upload feature on my form. It uploads the image when triggered by the onChange event for the file input, but then it uploads again when submitting the form. Is there a way to prevent this duplicate upl ...

Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code: function doSomething(numRetries) { $.post('someURL', {retr ...

Modify the tooltip of the selected item in an ng-repeat loop in AngularJS

Upon clicking an element, a function is executed which, upon successful completion, should change the tooltip of that specific element. Within an ngRepeat loop, I have multiple elements displaying the same tooltip. However, I only want to update the toolt ...

Having trouble with the preview feature when resizing images

Before trying to implement the JSFiddle was working correctly: http://jsfiddle.net/qa9m7t33/ However, after attempting to implement it, I encountered some issues: http://jsfiddle.net/z1k538sm/ While trying to resize an image, I realized that this example ...

Is there a way to set a personalized callback function when closing a modal with MicroModal?

I've been utilizing MicroModal for showcasing a modal window. Everything seems to be working smoothly, except for when I try to trigger an event upon closing the modal. It's unclear to me where exactly I should implement this callback function. ...

What's the best way to add line numbers to source code on an HTML webpage after parsing?

I am currently working with AngularJS and MongoDB. In my MongoDB data, there are some text elements that contain a \n, causing each line to be displayed on a new line based on the occurrence of \n. However, I also want to add line numbers to each ...

Prestashop 1.7 - Enhanced top menu navigation with drop-down subcategories

While using the ps_mainmenu top menu with the default Prestashop theme, I noticed that the drop-down menu only works for parent categories and not subcategories. You can see this in the attached image and HTML code from Chrome. I'm looking for a way t ...

There seems to be an issue: [ng:areq] - Please visit the following link for more information: http://errors.angularjs.org/1

Hey there! I'm in need of some assistance. Just started learning Angular and tried setting it up like this. This is the structure of my files: AboutController.js function AboutController( $scope ){ $scope.data = { "data" : { "name ...

Having trouble with the Material-UI v1 Drawer component on the iOS 13 beta version

As we prepare for the upcoming iOS release, set to debut next month, it has come to our attention that the main navigation on our website is experiencing issues when accessed using an iOS device running the latest beta (iOS13). While the drawer opens as ex ...

Dynamic Dropdown Menu with AJAX, PHP, and jQuery

I am currently working with a file called ajax.php ' <?php class AJAX { private $database = NULL; private $_query = NULL; private $_fields = array(); public $_index = NULL; const DB_HOST = "localhost ...

Is there an advantage to pre-compiling jade templates for production in an express environment?

Is it advantageous to have a middleware that pre-compiles all .jade views for production use, or does this happen automatically when NODE_ENV is set to 'production'? I am investigating ways to accelerate jade rendering for production purposes. ...

Elements not following percentage in top positioning

I am facing an issue with resizing containers on my webpage. Despite using position: relative for everything, I am unable to properly adjust the size of the top containers using percentages. Any assistance would be greatly appreciated! ...

What could be causing the poor performance of WebGPU in my benchmark when compared to WebGL?

After running my benchmark code on the Latest Chrome Canary on Win11 and disabling vsync with unlocked fps, I noticed that WebGPU has around 1/3 the FPS of WebGL. I'm struggling to understand the reason behind this performance difference. Here is the ...

Having trouble determining the dimensions of a newly added element

I am using jQuery to dynamically add an image but I am unable to retrieve its dimensions (width and height). Below is the snippet of code from my HTML file: <input type="checkbox" id="RocketElement" data-id="1"> And here is the JavaScript/jQuery c ...

What is the best way to send JSON data from Express to a JavaScript/jQuery script within a Pug template?

Currently, I am facing a challenge in passing JSON data from an Express route to a .js file located within a .pug template. I have been attempting to solve this issue using the following method: The router: // Office Locations router.get('/office_lo ...

Getting node.js code to function in a web browser

As a newcomer to Node.js, I decided to create a chat application as a hands-on learning experience. My choice of library was ws. During my experiment, I discovered that Node.js code doesn't work directly in browsers, especially when it comes to requi ...

Upon loading, make sure to click on the link located within the third <li> tag

I am working with a list (<ul>): <ul class="options_inner"> <li><a data-dk-dropdown-value=".option1"></a></li> <li><a data-dk-dropdown-value=".option2"></a></li> <li><a data- ...

Tips for effectively handling unique properties of a React component (such as Redux integration and custom CSS) when sharing through NPM distribution

Question: How can custom Redux containers and CSS be effectively managed with NPM? It can be challenging to handle these custom files through traditional package distribution platforms like NPM, especially when they need to be edited in various projects. ...

Two vertical divs stacked on top of each other, each expanding to the entire height and width of the browser window

Is there a way to set the width and height of two divs on a webpage to match the dimensions of the browser window, requiring scrolling to view the second div? In addition, how can I ensure that the content within these divs is vertically centered? To ach ...