timeiscoffee timeiscoffee - 6 months ago 14
jQuery Question

Where does jquery clone render it's content?

Where does jquery clone object that is not appended to anything render it's content? It's not in the page DOM

Say I have this markup:

<div class="output">
<span class="label">hello world</span>
</div>


and run this script:

var cloned = $('.output').clone();
cloned.find('.label').html('<img src="x" onerror="alert(1);"/>');


Why does the alert run despite cloned jquery object not being appended anywhere?

Image isn't rendered anywhere so why is the image loading and onerror firing?

http://jsbin.com/xulilewogi/1/edit?html,js,output

Answer

Why does alert run?

img src "x" is not found


Edit, Updated

I was asking why cloned element is loading image when it is not rendered anywhere on the page DOM

Why does the alert run despite cloned jquery object not being appended anywhere?

That does not matter with <img> elements. For example, try

var img = document.createElement("img"); 
img.onerror = function() {alert(1)};
img.src = "x";

jsfiddle https://jsfiddle.net/eue0y6ny/

Note, the image is not appended to DOM, though request is made for resource set at src, and img.onerror is called.

Similarly, at .html('<img src="x" onerror="alert(1);"/>'), an <img> element is created with onerror event attribute attached. <img> src is requested, onerror is invoked when resource is not found.


See The img element at

When the user agent is to update the image data of an img element, it must run the following steps:

  1. ⌛ If selected source is null, then set the element to the broken state, queue a task to fire a simple event named error at the img element, and abort these steps.