2
var strHTML = "<div><img src='/fake/path/fakeImage.jpg'/><span id='target'>text to extract</span></div>";

var dom = $(strHTML);

var extractedText = dom.find("#target").text();
alert(extractedText);

When I convert the HTML string to a jQuery object, jQuery makes GET request to retrieve pictures as you can see in the network tab in the developer tools.

Network tab in developer Tools

JsFiddle

How can I convert a HTML string to jQuery object without downloading any resources from the parsed string ?

Note : jQuery.parseHTML does not return a jQuery object, you cannot use .find() for example.

KVM
  • 878
  • 3
  • 13
  • 22

2 Answers2

2

I don't think this is possible, since its not jQuery (or javascript) that does the image loading but the browser - as soon as a src attribute is set on an img element the browser will attempt to download it.

One thing you can do is change the element name from img to something else before building the dom, or change the src attribute to something else, for example:

// change the <img> elements to <my_img> to avoid image fetching
strHtml = strHtml.replace(/<img /gi, "<my_img ").replace(/<\/img>/gi, "</my_img>");

// or the 2nd alternative:  change the src attribute of images
strHtml = strHtml.replace(/<img([^>]*?) src=/gi, "<img$1 my_src=")

// now its safe to parse into DOM - no images will be fetched
var dom = $(strHtml);

note this simple "search and replace" may replace texts other than the elements you want, but it may be sufficient for your use case.

Iftah
  • 9,512
  • 2
  • 33
  • 45
2

You can feed it through $.parseXML first:

var strHTML = "<div><img src='/fake/path/fakeImage.jpg'/><span id='target'>text to extract</span></div>";

var dom = $($.parseXML(strHTML));

var extractedText = dom.find("#target").text();
alert(extractedText);
Drazen Bjelovuk
  • 5,201
  • 5
  • 37
  • 64
  • 1
    This will work as long as the HTML string is well-formed XML – Dave Sep 02 '15 at 22:46
  • 1
    Unfortunatly it doesn't work on a real html page (not in my case at least), I get "Invalid XML" error. But it's fine on my example which is very simple. – KVM Sep 02 '15 at 22:49
  • @dave is right, the parseXML will fail if, for example, the html contains `
    ` or `
    ` which are perfect html but invalid xml
    – Iftah Sep 02 '15 at 22:49