Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onslotchange — handling the slotchange event

onslotchange specifies a handler for the slotchange event. In Shadow DOM, this event can fire when a slot’s assigned nodes change or when a direct child is added to or removed from a slot with no assigned nodes.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

HTML: <slot onslotchange="handleChange(event)"></slot>
JavaScript: slot.onslotchange = (event) => { /* handle change */ };

onslotchange is a global HTML event handler attribute for slotchange, with a corresponding JavaScript property of the same name. It is typically used on a slot element in Shadow DOM. The attribute itself neither creates a slot nor assigns content to it.

The event can fire when the assigned nodes change, for example when a matching child of the host is added or removed. If the slot has no assigned nodes, adding or removing a direct child of the slot (part of its fallback content) can also fire the event, even though the assigned-node list stays empty. It is not a general notification of changes inside an already assigned element. Read the current assignment with assignedNodes() or assignedElements().

The attribute value is JavaScript code. Inside the handler, event and this refer to the event and the handling element respectively. Assigning a function to the onslotchange property replaces the previous handler; addEventListener('slotchange', handler) allows independent listeners. A CSP policy can block attribute-based code.

The example creates a default slot and adds one child to its host. Handling is asynchronous: check the result after event delivery, not immediately after append().

Examples

<!doctype html>
<meta charset="utf-8">
<title>onslotchange example</title>
<div id="host"></div>
<pre id="result">Waiting</pre>
<script>
  const host = document.getElementById('host');
  const result = document.getElementById('result');
  const root = host.attachShadow({ mode: 'open' });
  root.innerHTML = '<slot onslotchange="document.getElementById(\'result\').textContent = this.assignedNodes().length"></slot>';

  const item = document.createElement('span');
  item.textContent = 'Hello';
  host.append(item);
</script>

Result

1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources