Using the $.get() method within a loop of .each(), retrieve the specific $(this) value within the $.get function

Apologies for the poorly worded question, but I'm struggling to find a better way to phrase it.

I'm currently working with a .each() loop where I need to update a specific css() parameter of each item in the loop. However, I can't seem to get it right.

Below is the code snippet I'm using:

$(document).find('.test').find('p').each(function(){
    var test=$(this).css('background-image').split('(')[1].split(')')[0];
    var retGet=$.get(test);
    $(this).css({
        'background-image':  'url(data:image/png;base64,'+retourGet.responseText+')'
    }); 
});

I've omitted the url editing part (the second line provides the current url which I edit).

Unfortunately, when running this code, I receive undefined values in my css parameters. It appears that the $.get loading process isn't complete before I try to change the background image.

I attempted something like this:

$.get( test, function( data ) {

});

But I'm unsure how to access the individual $(this) element within the .each() loop here.

Answer №1

Utilize the parameters provided by the each function:

$(document).find('.example').find('span').each(function(index, element){
    var source=$(element).css('background-image').split('(')[1].split(')')[0];
    var response=$.get(source);
    $(element).css({ // element represents the current .example object
        'background-image':  'url(data:image/png;base64,'+response.responseText+')'
    }); 
});

If you wish to incorporate the callback function from .get, make use of the element variable:

$.get( source, function( data ) {
 $(element).css({ // element is the current .example object
        'background-image':  'url(data:image/png;base64,'+data+')'
    }); 
});

Answer №2

There are a couple of ways to tackle this issue. One option is to follow the approach outlined by @celerno (which is likely the recommended course of action)

Another solution involves utilizing function binding to ensure that the this pointer is correctly set.

$.get( test, function( data ) {
    $(this) // will now behave as expected
}.bind(this));

Note: The built-in bind method is only supported in browsers that conform to ECMAScript 5 and newer standards. Consequently, this technique may not function properly in older browsers such as IE8 and earlier versions.

Answer №3

Utilize the index and value parameters when using the each method:

$(document).find('.test').find('p').each(function(i, val){
    var test=$(val).css('background-image').split('(')[1].split(')')[0];
    var retGet=$.get(test);
    $(val).css({
        'background-image':  'url(data:image/png;base64,'+retourGet.responseText+')'
    }); 
});

It's important to note that the function() should be replaced with function(i,val) and $(this) should be replaced with $(val). For more information, refer to: http://api.jquery.com/jquery.each/

(Encountered this issue before - was quite frustrating)

Answer №4

If you don't provide your fiddle, it's hard for me to diagnose your issue. However, I encountered something similar in the past.

You can try testing out this solution: http://codepen.io/gc-nomade/pen/bscaF

Here are some explanatory comments:

$(".test").children().each(function() {
  var element = $(this).get(0);
  $(this).attr("data-tag", element.nodeName);

   if (element.nodeName == 'P') {
     var test = $(this).css('background-image').split('(')[1].split(')')[0];
     var response = $.get(test);   
    // this.style.background = 'url(data:image/png;base64,'+response.responseText+')';// does not work here out of context
    //  this.css('background','blue'); //does not work
     this.style.background = 'red';
   }
})

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

Connecting Node.js Post script to an HTML form: A step-by-step guide

After successfully creating a RESTful API, I tested it using Postman and everything worked as expected. The test is executed from an index.js file where the routes are saved as shown below. const config = require('config'); const mongoose = requi ...

Methods for effectively redirecting a Java ResponseWriter

I am looking for a way to view the output of my ResponseWriter directly in standard output for debugging purposes. Unfortunately, since the response will be handled by JavaScript, I am unable to see the output there. Is there a simple solution to redirect ...

Transmitting the identification number of a post with the help of J

I am currently working on a while loop in PHP that fetches associated results from a query and displays them within a class identified by the user who created the post. My goal is to send the id of the class to PHP, similar to how I am sending the num vari ...

Selecting Laravel lists by month option

I'm encountering a problem here. The error message reads "Too few arguments to function App\Http\Controllers\ViewsController::OBviews(), 0 passed and exactly 1 expected" Here is my controller: public function OBviews($date) { ...

Selenium Python can be used to save a web page as a

Trying to print a webpage as a PDF with headers and footers to mimic the output from Google Chrome. Any suggestions? Experimented with PhantomJS but couldn't get it to include headers and footers. from selenium import webdriver import selenium def ...

Having trouble with the HTML5 canvas for loop not rendering the initial object in the array?

Essentially, I'm attempting to iterate through each letter in a text string (specifically the text "marius"). However, there's an issue where the first letter is not being displayed. When the text is "marius", only "arius" is drawn. I've exh ...

My attempt at creating a straightforward sorting function turned out to be ineffective

My attempt at creating a basic sorting function seems to be failing as it is still returning the original list instead of the sorted one. function sortByPopular (collection) { let items = collection.slice(); items.sort(function(a,b) { re ...

Tips on avoiding quotation marks in a Less variable containing a color identifier

I'm currently working on an HTML/CSS project where I aim to establish classes for labels and texts based on their color. For instance: .text-red{ color: red; } .label-white{ color: white; } In order to achieve this, my approach involves cr ...

What is the best way to showcase my subscription form on a web browser?

I am encountering an issue with my code. My goal is to generate a subscribe form modal. Although I have incorporated the subscribe form in my HTML document, upon running the code in the browser, the subscribe section is not visible. Can anyone offer assist ...

Combining two flex elements with auto-growing capabilities in react-native

I am excited about using react-native to have a TextInput aligned with a MaterialIcons.Button in the same line. I have been trying to center these elements horizontally but haven't been successful with the code below: import React from 'react&apo ...

Locate the HTML code following an AJAX response

JavaScript code snippet: $("#category select").change(function(){ var category = $('select option:selected').html(); $.ajax({ type:"Post", url:"collectiepost.php", data:"category="+category, cache:"false" ...

Having issues with the Bootstrap tabs code provided in the documentation not functioning correctly

Exploring the world of Bootstrap 5 tabs led me to copy and paste code from the official documentation (https://getbootstrap.com/docs/4.1/components/navs/#javascript-behavior), but unfortunately, it's not functioning as expected: clicking on a tab does ...

Generating an error when the input is focused

Whenever I try to navigate to Facebook and focus on one of the registration input fields, an error pops up. I attempted to fix this issue by implementing some code, but unfortunately, it did not work as expected. _emptyCheck: function() { ...

What is preventing my ActionResult from accessing the value of this jQuery AJAX post?

I have integrated a JQuery-based pagination tool into a simple table graph and am facing an issue with passing the selected page number to the ActionResult responsible for generating a LINQ query. Despite confirming that the "pagenum" parameter is being po ...

Is it possible to maintain the sidebar while eliminating the scrolling JavaScript?

Looking to recreate the image display style on Facebook where pictures appear in a lightbox format. The challenge I'm facing is figuring out how they manage to have the sidebar with no visible scroll bar inside... If you want to see this for yourself ...

Concealing a column within an Angular Material table

I'm currently faced with a challenge involving an Angular Material table containing numerous columns. My goal is to selectively hide certain columns based on specific CSS media queries. This is the code snippet I have experimented with so far: HTML: ...

The function you are trying to execute in jQuery Mobile is not defined

I'm currently working on creating an external panel, but I've encountered some difficulties. Below is the HTML code: <html> <head> <title>My Page</title> <meta name="viewport" content="width=devi ...

Exploring the Integration of jQuery AJAX in a Contact Form

I would like to incorporate AJAX functionality into a contact form. Here is the current code I have... $("#contact_form").validate({ meta: "validate", submitHandler: function (form) { $('#contact_form').hide(); ...

Allow users to manually resize <td>'s within a platform

Looking for a way to allow users to manually resize a textarea and iframe in a system I am developing. Here's an example of what I mean: <body> <table width="100%"> <tr> <!-- I want the user to be able to re ...

Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data sour ...