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?
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?
var imgElement = $(htmlString).find("#my-img");
imgElement.prop('src', 'something else')`;
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
jQuery.find works, it only look for childrens. You can use the method described in this answer, or use a dummy element $('<div />').append(parsedHtml).find()