jerrygarciuh
jerrygarciuh

Reputation: 21988

Replacing root relative links with full URLs

I have a plugin that will be used multiple times in a single page. Each is contained in a div with a unique id.

The content of the divs will be received with images whose paths need to be prepended with different domains. Eg

<div id="mydiv"><img src="/images/somepic.jpg"></div>

My current function does locate the images correctly and modify them:

jQuery("#mydiv img[src^='/']" ).prop('src',
  function( _idx, oldHref ) {
    return 'http://example.com'+oldHref;
  }
);

However it sets their src to http://example.comhttp://thecurrentsite/images/somepic.jpg even though the source started with / and did not contain thecurrentsite.

How is thecurrentsite URL getting into the oldHref passed by prop()?

Upvotes: 0

Views: 59

Answers (2)

patrick
patrick

Reputation: 11711

prop returns the src as a full path use attr instead to get the original path

check this fiddle, it alerts the two versions:

<img src='test.html'>

$("img").prop("src") => full path
$("img").attr("src") => original relative path

Upvotes: 1

Ramiz Wachtler
Ramiz Wachtler

Reputation: 5683

If you use attr instead of prop, it works. Fiddle

Upvotes: 1

Related Questions