0

I am using jQuery on DOM elements that are not added to the DOM tree of the actual page, nor will be, to render some HTML and get it as a string.

Minimal example is simply evaluating:

$('<div><img src="foo.png"></div>').html()

Unfortunately, this causes the browser to try to load the image.

How can I prevent this?

This is in the context of a Chrome app, so a chrome-specific solution is acceptable.

In my use case, simply avoiding the DOM elements is not an option: In the actual code, the existing templating machinery uses DOM elements and jQuery to assemble the output. Similarly, I cannot simply replace src with data-src.

Joachim Breitner
  • 25,395
  • 6
  • 78
  • 139

1 Answers1

1

You can use DOMParser

var parser = new DOMParser();
var doc = parser.parseFromString('<div><img src="foo4.png"></div>', 'text/html');

The html is in doc.body.innerHTML if you need to do something with it

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • or just a DocumentFragment – Kaiido Dec 29 '16 at 10:57
  • This does not work for me, as the tempting code insists on using jQuery to assemble the different pieces of the output. – Joachim Breitner Dec 29 '16 at 11:00
  • I didn't but it sounds like a perfect fit : create DOM structure which is not part of the main DOM. I can't test it r-n so is there any issue ? – Kaiido Dec 29 '16 at 11:02
  • @Kaiido - I admit I thought so too, but no matter how I tried adding the HTML to a fragment, it would try to load the image – Jaromanda X Dec 29 '16 at 11:05
  • @JoachimBreitner - I see the problem, perhaps if you showed some more relevant code I could see if there's something that could be done – Jaromanda X Dec 29 '16 at 11:06
  • Ah weird... (the only way I thought was with innerHtml, since yes all imageElement created from the document will load...) should have tested before commenting. – Kaiido Dec 29 '16 at 11:07
  • Too bad. I was hoping for some trick like http://stackoverflow.com/a/20863227/946226 to work. But if the answer is “no, does not work”, feel free to post that as a proper answer. – Joachim Breitner Dec 29 '16 at 11:41
  • I tried using But the result was the same. – Stiffels Apr 16 '21 at 07:13
  • @Stiffels - what does two HTML comments have to do with this 4 and a half year old answer? – Jaromanda X Apr 16 '21 at 23:14
  • @JaromandaX - It is one of the ways to try to avoid loading the tag by adding the Fragment option to it. This comment-out syntax is generated by the browser when you make a clipboard copy of a selection in the browser. – Stiffels Apr 19 '21 at 08:04
  • @Stiffels - if you have an answer, please post one, don't confuse me with comments about comments that make no sense to me :p – Jaromanda X Apr 19 '21 at 23:16