user1694077
user1694077

Reputation:

Jquery: prepend content retrieved with .load

I'm loading an svg through ajax with jquery like so:

$("body").load("https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg");

Which loads just fine, but replaces all the content in the body. What I want it to do is prepend the loaded svg, so the svg does not replace everything but is inserted as the first element after <body>.

Upvotes: 0

Views: 90

Answers (4)

gulty
gulty

Reputation: 1076

Try this:

$.ajax({
  url:"https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg",
  method: "GET",
  dataType: "html",
  success: function(data) {
    $("body").prepend(data);
  }
})

You have to adjust the datatype in case you want to get different content (e.g. xml/json elements).

Works with your example - svg is right below the body and before your #svg div.

Upvotes: 0

kaytrance
kaytrance

Reputation: 2757

Well, you cannot just place an image retrieved into body like so. If you want to display image, just show it via img tag. If you retrieve data, you can use something like this:

$.get("https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg" )
  .success(function(data) {
      $("body").prepend(data.activeElement.innerHTML);
  });

The reason why your initial variant "worked" by showing an entire picture is that browsers can display image files, and your code just did that - the same would be if you just drag-n-drop an image into browser window.

Upvotes: 1

Wilmer
Wilmer

Reputation: 2511

Use $.get() then do prepend in the callback:

$.get( "https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg" )
  .done(function( data ) {
      $("body").prepend($(data).find("svg"));
  });

Upvotes: 1

Sadikhasan
Sadikhasan

Reputation: 18600

Try following code I checked it and working fine.

$("#svg").load("https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg");

Upvotes: 0

Related Questions