Reputation: 19150
I’m using JQuery 1.7.1. I have a block of well-formed HTML stored in a variable. Within this HTML there is a line,
<img id=“my-img” src=“…” />
Within my variable, how do I replace the value of the src attribute with something else?
Upvotes: 1
Views: 455
Reputation: 19150
Went ahead and used a generic Javascript solution, which was
myHtml = myHtml.replace(/<img id=\"my-img\" src=\"(.*?)\" width=\"66\">/g, "<img id=\"my-img\" src=\"" + imgSrc + "\" width=\"66\">");
Upvotes: 0
Reputation: 8814
jQuery can parse HTML strings for you, so you can work with it using jQuery API like you do when it's part of the document.
var htmlString = "<foo ... ></foo>";
var parsedHtml = $(htmlString);
parsedHtml.find('#my-img').prop('src', 'new value');
htmlString = parsedHtml.wrap('<div />').parent().html(); // in case you need it as string again
Upvotes: 2
Reputation: 7353
var imgElement = $(htmlString).find("#my-img");
imgElement.prop('src', 'something else')`;
Upvotes: 2
Reputation: 4370
var html = $('<tag>...<img id="my-img" src="" />...</tag>');
html.find('#my-img').attr('src', 'other src');
//or
//html.find('#my-img').prop('src', 'other src')
htmlFinal = html.html();
$('body').html(htmlFinal);
Upvotes: 0
Reputation: 61063
You wouldn't do a string replace. You'd access the object and change the attribute:
$(myVar).find('#my-img').attr('src', 'my-new-src');
Upvotes: 0