I have an html string I’d like to dump directly into an element. This html string contains some tags, and I need to prepend a path to their ‘src’ attributes.
Currently, I’m doing something like this:
// note, htmlString is coming in from an external xml file...
var htmlString = "<img src='img1.jpg'/><br/><img src='img2.jpg'/>";
var imgContainer = $('<div />');
imgContainer.append(htmlString);
var prefix = "some/path/to/img/";
imgContainer.find('img').each(function(i, el) {
$(el).attr('src', prefix + $(el).attr('src'));
});
This works, but I’m seeing failed resource loads of the non-prepended path. Seems as though the browser is attempting to load the images immediately upon creation of the imgContainer element, even though it’s not appended to the document. I’d like to avoid those failed loads.
I suppose I could parse htmlString before appending but it’s nice to just $.each() through the element after it’s created…
NOTE: I’ve learned through asking this question that creating a jQuery element via $(htmlString) immediately causes load attempts on all resources within htmlString. So, I have to manipulate htmlString in some way before packing it into a jQuery object.
You can try to parse the
htmlStringas XML, modify it, and then append it to the DOM.Something like this (Not sure if
XMLSerializerworks in all browsers, I think it’sthis.xmlin IE):DEMO: http://jsfiddle.net/de2dg/3/