Luke Kenny
Luke Kenny

Reputation: 3

Add absolute path to img in jQuery object

I want to pull some data from a particular div on an external site, pre-append a URL to img src links, which are relative, to make the absolute, then put that html in a div. Ignoring cross site issues...

jQuery(document).ready(function() {
  var $thePage = jQuery('<div>');
  jQuery($thePage).load("https://example.com div.myitem");
  jQuery($thePage).find('img').attr('src', function (i, src) {
    var newsrc = "https://example.com" + src;
    return newsrc;
  });
  jQuery("#testdiv").html($thePage);
});

The html is displayed in the div, but the img links aren't updated. Any ideas would be greatly appreciated!

Upvotes: 0

Views: 36

Answers (1)

James
James

Reputation: 22237

jQuery.load is asynchronous, so you should do stuff with returned data within a callback.

  jQuery($thePage).load("https://example.com div.myitem", function () {
    // replace stuff here
    // show output on page here
  });

Upvotes: 1

Related Questions