Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load an HTML string into jQuery without requesting images

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

like image 787
JamieD Avatar asked Jun 12 '12 23:06

JamieD


1 Answers

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.

like image 181
Nathan Wall Avatar answered Sep 19 '22 18:09

Nathan Wall