Is there a way to load an HTML string that contains image tags into jQuery without requesting the images? I want to be able to run selectors on the jQuery object to extract some information. Taking the following example:
var string = $('<p><img src="http://image.url/file.jpg" /></p>');
string.find('img');
The browser will make a request for http://image.url/file.jpg. I'm trying to find a way to do the same but without the browser making a request for the image.
Thanks
You can use an XML document to perform the search:
function searchXml(xmlStr, selector) {
var parser, xmlDoc;
if(window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlStr, "text/xml");
} else {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(xmlStr);
}
return $(xmlDoc).find(selector);
}
console.log(searchXml('<p><img src="http://image.url/file.jpg" /></p>', 'img').attr('src'));
See it in action: http://jsfiddle.net/na9Tt/
Keep in mind it is an XML document, not an HTML document, so some particular types of searches which are specific to HTML may not work exactly the same way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With