DOMSlots Utility

November 07, 2024

This JavaScript utility quickly retrieves element references. For example, say you’re opening a dialog and want to change its message.

domslots-util.js

function DOMSlots(itemEl) {
    let slotData = Array.from(itemEl.querySelectorAll('[data-slot]')).map(x => {
      return {
        key: x.dataset.slot,
        el: x,
      };
    });
    let slotObj = slotData.reduce((obj, item) => {
      obj[item.key] = item.el;
      return obj;
    }, {});
    
    return slotObj;
}

First, we identify the message element using the data-slot attribute. The attribute value should be a variable name without spaces or hyphens, preferably in camelCase.

<dialog class="_sampleDialog" open>
  <span data-slot="message"></span>
</dialog>

Next, we pass the parent container to the DOMSlots utility. This will return an object with keys that reference each data-slot element.

let slots = DOMSlots(itemEl);

slots.message?.replaceChildren('Hello from dialog');

The utility does not support multiple elements with the same data-slot attribute, so ensure each is unique.

Advantages of Using Data Attributes

Using attributes as identifiers works well in this case because, as long as each parent container is unique, there will be no conflicting selectors.

HTML

<dialog class="_sampleDialog" open>
<span data-slot="message"></span>
</dialog>

<dialog class="_confirmDialog" open>
<span data-slot="message"></span>
</dialog>

JS

// say hello dialog
{
  let $ = document.querySelector.bind(document);
  
  let slots = DOMSlots($('._sampleDialog'));
  
  slots.message?.replaceChildren('Hello from dialog');
}


// confirmation dialog
{
  let $ = document.querySelector.bind(document);
  
  let slots = DOMSlots($('._confirmDialog'));
  
  slots.message?.replaceChildren('Are you sure?');
}

Comments

Thank You

for your visit