Is it possible to attach a click event to a document fragment?

Tags:



What I have tried:

// creating elements
var container = document.createDocumentFragment();
var headline = document.createElement('h1');
headline.innerHTML = 'This is a headline.';

// attaching to DOM
container.appendChild(headline);
document.body.appendChild(container);

// attaching click event
container.addEventListener('click', function () {
    console.log(arguments);
});

This example does not work. The event is not triggered.

Is there any way to attach a click event to a document fragment or is it simply not possible?

Answer

The click event will not work in this case because document fragment is not appended to DOM structure. Here is what documentation says about it:

Various other methods can take a document fragment as an argument (e.g., any Node interface methods such as Node.appendChild and Node.insertBefore), in which case the children of the fragment are appended or inserted, not the fragment itself.

So “children of the fragment are appended, not fragment itself”. It means that click event bound to fragment is pretty much useless, because being outside of the DOM it’s not reachable for clicks.



Source: stackoverflow