Reputation: 35
I have all html tags string like below
var description = "<div class="header"> <div class="logo"> <a href="http://domain.com"> <img src="devimg/logo.png" class="showHome" alt="ssfdf" height="80px" /> </a> </div><div><img class="img1" src="devimg/sss.png"></img></div><div><img class="img2" src="devimg/.png"></img></div> </div>"
I have html string like above ,want to iterate all img tags and append some domain to src url
like <img class="img1" src="www.otherdomain.com/devimg/sss.png">
like this want add domain for every img tag. After replacing all want get whole html tags again with newly appended domain for img tags.
How can I do this one in jQuery?
Upvotes: 2
Views: 1853
Reputation: 35
this code has satisfied my requirment. data is html string.
var temp = document.createElement('div');
data = data.replace(/src=/gi, "tempsrc=");
temp.innerHTML = data;
$(temp).find( 'img' ).each(function() {
var oldSrc = $(this).attr("tempsrc");
$(this).removeAttr("tempsrc");
if(oldSrc){
$(this).attr("src", "clouddomain.com/"+oldSrc);
}
});
If you append any html content to dom element it loads the resources like images from ur domain by taking as relative path. In the above code replacing some temporary attribute then appending to the one dom element. then replacing the cloud url.
Upvotes: 0
Reputation: 672
You have to iterate through every img tag, get src and then change src on your img tag.
var otherDomain='www.otherdomain.com';
$('img').each(function(){
$(this).attr('src', otherDomain + '/' + $(this).attr('src'));
});
edit: someone was faster..
I think that Guy already posted solution with replacing string with new domain in src attribute. You can use regex or replace src attribute in img tag like this:
var otherDomain = 'www.otherdomain.com';
description = description.replace('src="', 'src="' + otherDomain);
Is this the answer you were looking for?
Upvotes: 1
Reputation: 5479
If this actually part of the DOM and not a string with jQuery you can run an each on all the img tags and change the src attribute something like this
$('img').each(function() {
$(this).attr('src', 'http://otherdomain.com' + $(this).attr('src'));
});
jsfiddle: http://jsfiddle.net/zVgpV/
If it's a string you'd have to regex it, your Regex will be something like this
str.replace(/src="(.*)"/, 'src="http://otherdomain.com/$1"')
Upvotes: 0