Blog>
Snippets

Fragment with Event Handling

Implement event handling on multiple elements within a single fragment to illustrate event management without extra DOM elements.
const fragment = document.createDocumentFragment();

// Create two buttons
const button1 = document.createElement('button');
button1.textContent = 'Button 1';
const button2 = document.createElement('button');
button2.textContent = 'Button 2';

// Append buttons to the fragment
fragment.appendChild(button1);
fragment.appendChild(button2);

// Function to handle click events
const handleClick = (event) => {
  console.log(`Clicked: ${event.target.textContent}`);
};

// Attach event handler to the fragment for event delegation
fragment.addEventListener('click', (event) => {
  // Check if the event target is a button
  if(event.target.tagName === 'BUTTON') {
    handleClick(event);
  }
});

// Eventually, the fragment must be added to the DOM
// Assuming `container` is the element to append our buttons
const container = document.getElementById('container');
container.appendChild(fragment);
This code creates a document fragment and appends two buttons to it. An event listener is attached to the fragment employing event delegation. All click events on button elements inside the fragment are handled by a single event listener, which then calls the handleClick function. The fragment is eventually appended to a predefined container in the DOM.