Can I associate a click event with a fragment of a document?

What I 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 does not fire.

Is it possible to associate the click event with a fragment of a document or is it simply impossible?

+4
source share
1 answer

In this case, the click event will not work because the document fragment is not added to the DOM structure. Here is what the documentation says :

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

, " , ". , click, , , DOM, .

+7

All Articles